In my Symfony 2 application I am using the FormBuilder to create a form for selecting data contained in a generated document.
$typeChoices = [
'001' => 'first factor',
'002' => 'another factor',
'003' => 'some surcharge',
'004' => 'custom discount',
'005' => 'another surcharge'
];
$formDownload = $this->createFormBuilder(array())
->add('category', 'entity', array(
'class' => 'MyApp\CategoryBundle\Entity\Category',
'choice_label' => 'name'
))
->add('type', 'choice', array(
'choices' => $typeChoices,
'multiple' => true
))
->add('download', 'submit', array(
'attr' => array(
'class' => 'btn-primary'
),
))
->setAction($this->generateUrl('myapp_data_download'))
->getForm();
The $typeChoices data is loaded from an EntityRepository - I just simplified the code for this demo.
That way, a select box is generated like that:
<select multiple="multiple" class="form-control" required="required" name="form[type][]" id="form_type">
<option value="001">first factor</option>
<option value="002">another factor</option>
<option value="003">some surcharge</option>
<option value="004">custom discount</option>
<option value="005">another surcharge</option>
</select>
How can I add a class attribute to each option? It must be created based on an attribute of the original data coming from the EntityRepository. Until now, I was not able to add a class attribute to the options when using the FormBuilder and I would like to avoid creating the form markup manually.