How to deal with the choice of "other" in EntityChoiceList in Symfony2 forms?

I have a model as described below:

http://yuml.me/diagram/class/[Product.BIZ0..*-1โ–บBrand]

I also have a form for creating a new product with an entity field creating a drop-down list containing all brands.

Now I want to add the value โ€œOtherโ€ to this list to allow the user to manually specify the brand in another text box.

The question is: is there a clean way to manage this case (for example, adding to the list a value of "Other", which is not an entity and obtaining validation of the form for work) from Symfony2 Form?

+4
source share
1 answer

You can do this in two ways:

  • You can subscribe to an event of the form FormEvents::BIND_CLIENT_DATA . In the event method, you can create a new Brand object from the text, save it and set the id to the form by calling $event->setData($data) . See this entry in the cookbook.

OR

  • You can add a data converter. In your reverseTransform method reverseTransform you can create + save the object and return its identifier. See this cookbook article .
+2
source

Source: https://habr.com/ru/post/1414882/


All Articles