Skip to content
Advertisement

Symfony reusable AJAX select / ChoiceType

I want to create a reusable AJAX-based select (select2) using Symfony form types and I’ve spent quite some time on it but can’t get it to work like I want.

As far as I know you cannot override options of form fields after they have been added, so you have to re-add them with the new config. The Symfony docs also provide some examples on how to dynamically add or modify forms using events. https://symfony.com/doc/current/form/dynamic_form_modification.html

I’ve managed to create my AJAX based elements in the form and it’s working but not completely reusable yet:

  • Form field extends Doctrine EntityType to have full support of data mappers etc
  • Form field is initialized with 'choices' => [], so Doctrine does not load any entities from db
  • Existing choices on edit is added during FormEvents::PRE_SET_DATA
  • Posted choices are added during FormEvents::PRE_SUBMIT

The current setup works but only in the parent form. I want to have my AjaxNodeType completely reusable so the parent form does not need to care about data handling and events. Following the 2 examples, parent and child form. Here with event listeners in both, but of course they should only be in one.

Is it simply not possible in single element types to replace “yourself” in the parent form or am I doing something wrong? Is there any other way to dynamically change the choices?


Parent form This works!

JavaScript

Child form / single select This does NOT work. On POST the fixedNode field is not set to the form data-entity.

JavaScript

Advertisement

Answer

Again, answering my own Questions 🙂 After spending some more time on it I got a working solution. And maybe it will be helpful for someone.

  • I’ve switched from EntityType to ChoiceType as it only made things more complicated and is not actually needed
  • multiple and single selects need different settings/workarrounds (like by_reference), see the line comments below
  • re-adding yourself to the parent form works, I don’t know why it did not before…
  • beware of endless-loops when re-adding / re-submitting values

The main re-usable AjaxEntityType that does all the logic without reference to any specific entity:

JavaScript

Actual usage with specific entity and ajax endpoint:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement