In advanced Drupal 8+ Development you may run into this error:
Exception: Serialization of 'Closure' is not allowed in serialize() (line 14 of core/lib/Drupal/Component/Serialization/PhpSerialize.php).
In my case, it happened when implementing larger class structures and especially complex custom forms (extending FormBase
).
This typically happens, if in your form you're using Dependency Injection or object attributes and a referenced object can not be serialized by Drupal (for caching).
My first workaround was using
$form_state->disableCache();
in the form, which made the error go away but therefor broke form handling. Field values were getting lost on form submit on the multistep Drupal form.
So I needed to find the reason behind this issue and how to fix it!
DependencySerializationTrait to the rescue
Drupal Core offers the wonderful DependencySerializationTrait
to help in such cases. It adds magic sleep()
and wakeup()
implementations.
But wait, FormBase already implements DependencySerializationTrait
!
Correct, and this is the important part: Should you run into this error, then presumably it's not the form itself and its dependencies that can't be serialized, but an object which is referenced by the form.
So you need to find out, which of your Form object properties is the one that can't be serialized and add the DependencySerializationTrait
there.
Afterwards the error is gone, and the form should work as expected!