Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to select option in Symfony FormBuilder

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.

like image 674
dhh Avatar asked Sep 27 '22 05:09

dhh


1 Answers

New in Symfony 2.7: Choice form type refactorization

In Symfony 2.7 this form type has been completely refactored to support dynamic generation for labels, values, indexes and attributes. This is now possible thanks to the new options choice_label, choice_name, choice_value, choice_attr, group_by and choices_as_values.

You can for example generate dynamic choice label.

Example:

$builder->add('attending', 'choice', array(
    'choices' => array(
        'yes' => true,
        'no' => false,
        'maybe' => null,
    ),
    'choices_as_values' => true,
    'choice_label' => function ($allChoices, $currentChoiceKey) {
        return 'form.choice.'.$currentChoiceKey;
    },
));

In your case, you want manipulate the attribute class of each option.

Example:

$builder->add('attending', 'choice', array(
    'choices' => array(
        'Yes' => true,
        'No' => false,
        'Maybe' => null,
    ),
    'choices_as_values' => true,
    'choice_attr' => function ($allChoices, $currentChoiceKey) {
        if (null === $currentChoiceKey) {
            return array('class' => 'text-muted');
        }
    },
));

Hope it will help.

like image 128
zilongqiu Avatar answered Oct 11 '22 17:10

zilongqiu