9

I could do this with Javascript, but I was wondering if I could add a css class to specific symfony2 form choices (not the choice field itself, but the individual choices).

For example I want to apply different css styles to individual 'option' tags inside a 'select'. I could only find a way to add a class to the tag.

Thanks in advance.

David Undy
  • 943
  • 2
  • 7
  • 12

4 Answers4

11

I think you can simply do:

{{  form_widget(form.name, { 'attr' : { 'class' : 'myClass' } })  }}

... as explained here, without creating your own form style.

gremo
  • 47,186
  • 75
  • 257
  • 421
4

You can override the layout of specific widgets in your form, which means you can override the way the select renders and put in custom code to check what the value of the option is and output your custom class there.

You need to apply a custom layout to your form, like so

{% form_theme form 'form_theme.html.twig' %}

Then inside the layout file you need to override the specific field for that specific form (unless of course you want to edit the choice_widget directly in which case all fields that use choice will have the functionality).

To do that you have to copy the widget, so choice_widget, then name it [_formName_fieldName_widget]

So if your form name was events and your field name was requireTickets, it'd be _events_requireTickets_widget

Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
CriticalImpact
  • 690
  • 4
  • 12
  • Thank you, I didn't need the class name to apply specific styles, but a few jQuery plugins depended on – David Undy May 28 '12 at 03:42
4

The answers that were already provided are very good, and I think @CriticalImpact's is the most flexible. But I just wanted to mention that if you're using a form class, you can also add extra attributes to the field via the form builder definition itself:

class SomeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('someField', "text", array("attr" => array("class" => "someCssClass")))
            ->add("save", "submit");
    }
}

I've found this helpful for basic forms, because it still allows you to make a simple {{ form(someForm) }} call in your Twig file.

(Note that this solution still has the drawback that @CriticalImpact mentioned above)

Community
  • 1
  • 1
Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
3

Add attributes like CSS styles to individual choices can nowadays be achieved with choice_attr, e.g.:

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('attending', ChoiceType::class, array(
    'choices' => array(
        'Yes' => true,
        'No' => false,
        'Maybe' => null,
    ),
    'choice_attr' => function($val, $key, $index) {
        // adds a class like attending_yes, attending_no, etc
        return ['class' => 'attending_'.strtolower($key)];
    },
));
André
  • 2,042
  • 1
  • 23
  • 26