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.

      // 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.

  • Hey hey, welcome back. :) Without seeing your code we probably can't tell you much more then there's in the docs. See Dependency Injection for a Form.
    – leymannx
    Oct 14, 2019 at 9:52
  • @leymannx Hey, I exactly using like that. And as I said it works except on final submit, and it turns out the Drupal cache is faulty... Oct 14, 2019 at 10:08
  • 1
    Sounds like a core bug to me. But still, we didn't see your code. So, hard to tell, hard to reproduce.
    – leymannx
    Oct 14, 2019 at 10:49

1 Answer 1


Haha, I've fount it finally. The problem was the properties were private. And the serialization trait wasn't able to save the values and when it loaded back it became null.

  • Thank you, really saved me a lot of time here! Mar 4, 2020 at 9:48
  • And if I don't miss it, the property can be protected or public, but not private because it can't see/use the trait the private properties. Mar 5, 2020 at 12:29

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