How to store temporary data within a FormState object when using the Form API
When building a form in Drupal 8, a FormState object always accompanies the form render array. The form state object persists its data through the form builder, validation, and the form submission.
With the FormState object, you can use
$vals = ['name' => 'bob', 'age' => 50 ]; // save the data. $form_state->setStorage($vals); // retrieve the data $vals = $form_state->getStorage(); $str = $vals['name'] . ' is ' . $vals['age'] . ' years old.';
This replaces the Drupal 7 method of setting values in a key in the then-associative array form_state.