Create and Validate a Choice List in a Symfony 2 Form
There is a lot of magic going on in the Symfony 2 form component, and while this magic is frequently convenient and borderline awe-inspiring, it sometimes has the unpleasant side effect of making it unclear how to do more fine-grained tasks within the form. A standard select list can be created using Symfony’s choice field type; it is pretty clear how to create a new choice field with simple, non-dynamic options (e.g. gender), but it gets a little more complicated when you want to create and validate a dynamically generated choice list.
When creating your choice field, you can specify which options are available by either passing an array of options (“choices”) or by passing a custom object that implements \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface (“choice_list”). For this article, I will be focussing on the latter, but this can all be very easily adapted to a simple choices array.
Choice Lists and Doctrine 2 Entities
If the model that you bind to your form type is a doctrine 2 entity, then chances are the vast majority of your choice field’s form logic will be taken care of for you. If you add a form field that matches an entity property that has an association to another entity, then Symfony guesses the correct form field type, retrieves the form field options, and even validates your input to make sure it is a valid option. It is, for the lack of a better term, awesome:
We’ll need an entity:
We’ll also need a form type:
Tie it all together with your action:
With that code in place, your form will have a select field that lists all categories as options, and validation will ensure that not only is a category provided but also that the category is one of the available options. Note: your category entity will need to have a __toString() method defined as this is used as the human-readable component of a select option.
Creating and Validating Non-Entity Models
Sometimes it is necessary to use a model in your form type that is not itself a Doctrine entity. Personally, I have encountered this mostly when dealing with deletion forms. Consider this scenario: let’s say you are adding functionality to delete a specific Category entity (the same category that is referenced in our previous Post example), but in order to delete a category, you need to choose where all of its child posts should be moved. In this case, you want to display a select field with all possible categories, but you don’t have the wonderful benefits of a doctrine entity with an association defined.
In this situation, create a new model to represent your deletion parameters, attach it to a form that is designed to render and validate the available parameters, and then use that model to perform the necessary business logic to move the child posts and delete the category. Again, let’s go with an example.
The model here is a little more complex than the previous entity; pay careful attention to the “assert” annotations that I use here:
The NotBlank assertion on the $inheritingCategoryId ensures that a category id is required. The Callback assertion on the class ensures that the given category id is actually one of the available options. Note: Callback assertions cannot be placed on properties.
Now for the form type:
In this form type, we have to do a little more leg work than we did before. The form builder doesn’t have enough information to guess all of the field’s details like it did with the doctrine entity, so we needed to specify that this is a “choice” field, with a custom label, and populated by a specific choice_list.
Next up? You guessed it; the action:
The controller above is a little rough. I included a lot of logic in there that should really go into a separate service, but I didn’t want the complication of the example getting in way of the meat of the issue.
That’s it! When you render the form, it will provided a Symfony 2 choice field rendered as a select field that is populated with all of the categories (except the one we’re deleting). When you submit the form, it will check to make sure that not only is a category selected but also that the selection is actually one of the categories in the system.
I’m still only breaking the surface of the Symfony 2 form component, and I am finding that for all of incredible convenience that is provided for very common functionality there is likely an equal amount of frustration when trying to implement more specific pieces of functionality. That said, the component is certainly powerful, and I haven’t yet come across a scenario that it couldn’t handle.
Know of an easier way to do this? By all means let me know! I am eager to simplify processes like this as I expect to be doing this kind of thing frequently.
Edit (Aug 08 2010 4:40pm):
@Bernhard has provided an approach that seems to be much more in line with the usage that symfony devs envisioned. He notes that the entity field type takes care of validation for you and provides a convenient way to populate the select options as well. I’ve revised his example code only so much as to fit with the previous examples and execute properly:
Deletion parameters model:
I think this approach is much clearer than my original example. Thanks Bernhard!