As far as I can see, there are two ways of storing temporary data when working with complex forms in Drupal 8.

  1. $form_state->set('key', 'value'). The value ends up in $form_state['storage']['value'], and I can use it other places because it is passed around from function to function.

  2. Make a non-static property inside class MyForm extends FormBase. The value is also accessible everywhere I need it, since all of the form functions are in one class.

After browsing through a lot of core EntityForm code today, it seems that both are used! Is any of the above necessarily "better" or more in line with "The Drupal Way"?

Related question: It seems that there is a 1:1 mapping between an instance of MyForm and the $form_state variable. Why then, is $form_state not implemented as a non-static class property? Then it wouldn't be necessary to pass it from function to function. The same can be asked of the $form variable.

  • 1
    #1 is the traditional method with the Form API and probably is more compatible with AJAXy stuff.
    – mradcliffe
    Jan 31, 2017 at 13:47

1 Answer 1


While the storage in $form_state can be cached, the class property can't. So if you build a multistep form you would need to use the first option.

And a validate or submit function is not necessarily in the same class or in no class at all if it is defined in a hook. This also answers the related question.

  • 1
    Indeed ... I tested this, and it seems that the instance of MyForm loses its properties, while $form_state['storage'] keeps its values. Jan 31, 2017 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.