I followed the advice from this link and migrated the code populating my ajax into buildForm(), and all is well. Select list is populated by ajax and elements are preserved even after form submit. Problem is that I get the following error when I try to submit the form -
The value you selected is not a valid choice
I've tried adding the popular
'#validated'=TRUE option to my ajax select, but this causes 2 things to happen
- My ajax callback only successfully replaces the content of the select once, subsequent calls have no effect whatsoever, the old content of the select remains
- I get a really bad error when I try to
submit the form
"Website encountered an error". Checking the logs shows the following:
[client ::1:40776] TypeError: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 390 in /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 537 #0 /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php(390): Drupal\Core\Field\WidgetBase->massageFormValues()\n#1 /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php(232): Drupal\Core\Field\WidgetBase->extractFormValues()```
So if I use
'#validated' = TRUE, my ajax callback runs only once and shows the error above on form submit,
And if I remove
'#validated'=TRUE, my form fails to submit and shows
"You have selected an invalid choice" error".
I even tried to update the
$form_state variable to contain the same
#options values populated by my ajax callback and nothing changes, also
$form_state->setRebuild(TRUE) does nothing.
I'm almost giving up the idea of using ajax at all, since I've spent more than a week debugging just an ajax select element. First, the ajax callback wasnt being reached at all, now ajax populate happens, but cant submit form. It's just that I have this feeling that I've done 90% of the work involved, its just remaining 1 thing which I dont know. That remaining 10% is what I decided to throw this to the community. I'm sure someone else must know! Thanks for your help, guys...