I have a class that extends FormBase
and there are 6 services that are injected into the class via Dependency Injection (DI). My problem is when I submit the form it says to a class property that normally should be injected, it's NULL
and can't be called the load()
function on NULL
. However when I debug, I clearly see all the dependencies are injected to the class and saved to the properties, but until the execution reaches the validation/submit function somehow it became all property to NULL
. Why does this happen? How can I use DI in the form validation/submit phase? I'm really thinking if this class is not a deserialized cached version...
Extra info this form also has an ajax function where the DI works fine.
I went a bit deeper into the system, after the classfinder creates my form with the injected things and saved into this place: $form_state->getBuildInfo()['callback_object']
, I found it out the problem is the cache. (/core/lib/Drupal/Core/Form/FormCache.php:149
)
protected function loadCachedFormState($form_build_id, FormStateInterface $form_state) {
if ($stored_form_state = $this->keyValueExpirableFactory->get('form_state')->get($form_build_id)) {
// Re-populate $form_state for subsequent rebuilds.
$form_state->setFormState($stored_form_state);
// If the original form is contained in include files, load the files.
// @see \Drupal\Core\Form\FormStateInterface::loadInclude()
$build_info = $form_state->getBuildInfo();
The system loads the formstate from the cache with the following lines, the $stored_form_state
contains the cached state, without any dependencies, and the $form_state->setFormState($stored_form_state);
line overwrites my formstate which contains the right properties with the DI classes... And that's a problem.