Symfony Ajax populated ENTITY field handle
If you use an ENTITY type field in your formType, and if you populated this field with Ajax, you can have this error :
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[tag] = 2Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "tag": The choice "2" does not exist or is not uniqueCaused by:
Symfony\Component\Form\Exception\TransformationFailedException
The choice « 2 » does not exist or is not unique
I have a user Entity with a ManyToOne relation with a Tag entity.
In my form, when I select the user, an AJAX request retrieve all the user’s tag, and add the options on the select element.
But Symfony doesn’t know about these values, and the validation fails when the form is submitted.
After lot of tests, with data transformer, listener, both, I succeed with a simple event subscriber following this symfony doc page http://symfony.com/doc/2.7/form/events.html#event-subscribers.
Basically, the event subscriber occurs on the pre_submit, take the ID of the TAG, and add an entity field with a custom query who retrieved the good tag entity.
Enough talk, more code 🙂