Drupal 8 - How to pass data between form validate/submit callbacks
Similar to Drupal 7, we are able to pass custom data between form validate/submit callbacks.
In Drupal 8, there are two way of setting a key => value to $form_state: set a single key => value or multiple keys => values.
To set a single key, we can use set() method that is defined in FormStateInterface interface.
// Pass a key => value to other submit callbacks. $form_state->set('custom_key1', 'custom_value1');
To pass multiple keys => values, we can use the method setFormState() that gets an array as parameter and will add these array to form_state's storage.
// Pass multiple key => value to other submit callbacks. $form_state->setFormState(array( 'custom_key2' => 'custom_value2', 'custom_key3' => 'custom_value3', ));
To read these values from another validate/submit callback, you can use: get() or getStorage() methods.
// Get a value by key. $custom_value = $form_state->get('custom_key1'); // Get all keys => values. $storage = $form_state->getStorage();