Problem/Motivation
When a Drupal form uses AJAX, member variables lose their values when submitForm() is invoked.
Steps to reproduce
- Create a custom form with AJAX
- Add a
private RendererInterfacemember variable to the class - Use dependency injection to initialize the variable in the constructor
- In the
submitForm()method display a message indicating whether the member variable's value is empty or set - Load the form and submit it
- Read the message displayed by
submitForm()
Proposed resolution
Ensure that the object handling the submitForm() method is a properly initialized instance of the custom form class.
Remaining tasks
Fix the bug.
User interface changes
N/A
API changes
N/A
Data model changes
N/A
Release notes snippet
Fixed bug in initialization of form objects with AJAX.
| Comment | File | Size | Author |
|---|---|---|---|
| #2 | form_mystery.tgz | 1.59 KB | bkline |
Comments
Comment #2
bklineI have provided a repro case demonstrating the steps given above.
Comment #3
cilefen commentedI think this may be more of a support request. Does https://drupal.stackexchange.com/questions/231436/form-ajax-not-working-... explain what you are seeing?
Comment #4
bklineI don't think so. I did, however, get some insight from Conrad Lara (@cmlara) in the Slack #support channel. Apparently Drupal sometimes (but not always) serializes the instance of the
FormBase-derived class and then reconstitutes most of it, invokingsubmitForm()on this partially-resurrected instance. In the process it drops theprivatemember variables on the floor. "Sometimes" likely means "when AJAX is in play" in this context. As far as Conrad is aware, this behavior isn't documented anywhere. But sure enough, when I replaceprivatewithprotectedin the repro code I posted the form works correctly. I will edit the original issue summary to clarify that it'sprivatemember variables which are discarded.Comment #5
bklineComment #6
ddavisboxleitner commentedThis has been an issue for us as well. Switching all private variables to protected works to preserve the data in those variables during AJAX calls.
There is documentation about the serialization issue: https://www.drupal.org/docs/drupal-apis/services-and-dependency-injectio...
Comment #8
smustgrave commentedShould this be re-opened? If no response in 3 months will close out.
Comment #9
bklineThe status says "Maintainer needs more info" but it's not clear what additional information is needed. The behavior doesn't match the documentation. That's the definition of a bug. Data loss in most contexts means serious bug.
Comment #10
smustgrave commented