PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Create and Validate a Choice List in a Symfony 2 Form

Note: This article was originally published at Planet PHP on 19 April 4800.
Planet PHP

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:

namespaceAEpixa\Entity;useADoctrine\ORM\MappingAasAORM; /** A*A@ORM\Entity A*/ classAPost { AAAA//A...AotherApostAproperties AAAA/** AAAAA*A@ORM\ManyToOne(targetEntity="Epixa\Entity\Category") AAAAA*/ AAAAprotectedA$category; AAAA//A...AappropriateAgettersAanAsetters }

We'll also need a form type:

namespaceAEpixa\Form\Type; useASymfony\Component\Form\AbstractType, AAAASymfony\Component\Form\FormBuilder; classAPostTypeAextendsAAbstractType { AAAApublicAfunctionAbuildForm(FormBuilderA$builder,AarrayA$options) AAAA{ AAAAAAAA//A...AaddAotherAappropriateAformAfields AAA

Truncated by Planet PHP, read more at the original (another 28849 bytes)