I try to create the following field :
<select name="test">
<option value="1">a</option>
<option value="2">b</option>
<option value="3" style="font-weight: bold; color: red;">c *</option>
<option value="4">d</option>
<option value="5">e</option>
</select>
This creates a 2-color selectbox :

But in Symfony2, I do not know how to apply a class to a single option.
If in my view I do :
{{
form_widget(myForm.test, {
'attr': {
'class': 'red',
}
})
}}
Or if in my form I do :
$builder->add('test', 'choice', array(
'required' => true,
'choices' => array('a', 'b', 'c *', 'd', 'e'),
'attr' => array('class' => 'red'),
));
The attribute is stored into the <select> tag and apply to the whole selectable values.
Edit
I solved the problem using jQuery :
1) in my view I put :
{{
form_widget(myForm.test, {
'attr': {
'class': 'starred-select',
}
})
}}
2) in my javascripts, I put :
$('.starred-select option').each(function() {
if ($(this).text().substr(-2) == ' *') {
$(this).addClass('red');
}
});
Of course, my values can’t finish by a star.
How can I apply a class to an <option> tag in Symfony2 ?
You’ve to override the way your widget choice field is rendered.
Form Theming allows you to customize every part of your form. Even base form blocks can be overriden.
The best method to do this is to copy the default block from form_div_layout.html.twig
(In your case you’ve to override the
widget_choice_optionsblock)You can also customize your block at different levels of your application. Take a deeper look at the documentation, it includes fully explained examples.