symfony/symfony — pull request #10309 by florianv (2014-02-21 19:49:48+00:00)
Title: [Form] Implemented attributes for choices

| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | yes
| BC breaks? | dunno ?
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets |
| License | MIT
| Doc PR |

This pull requests add attributes support for choices.
I needed to add micro data attributes to `option` elements for select2 templating, but it can also be useful to disable options.

There are three ways to apply attributes to choices :

### By specifying the choices_attr option

Note: It works only when using `choices`. See below for when using choice lists.

```php
$builder->add('choice', 'choice', null, array(
'choices' => array('a' => 'A', 'b' => 'B', 'c' => 'C'),
'choices_attr' => array(
'a' => array('disabled' => true, 'data-foo' => 'bar'),
'c' => array('disabled' => true, 'data-bar' => 'baz'),
),
));
```

### By passing the attributes to the choice lists

```php
$builder->add('choice', 'choice', null, array(
'choice_list' => new SimpleChoiceList(
array('a' => 'A', 'b' => 'B', 'c' => 'C'), array(),
array(
'a' => array('disabled' => true, 'data-foo' => 'bar'),
'c' => array('disabled' => true, 'data-bar' => 'baz'),
)
)
);
```

### By modifying the views

```php
class SomeType extends AbstractType
{
public function finishView(FormView $view, FormInterface $form, array $options)
{
foreach ($view->vars['choices'] as $choice) {
if (!$choice->data->isEnabled()) {
$choice->attributes['disabled'] = true;
}
}
}
}
```