David Undy
David Undy

Reputation: 953

How can I add css classes to specific symfony2 form choices?

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.

Upvotes: 9

Views: 11607

Answers (4)

André
André

Reputation: 2142

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)];
    },
));

Upvotes: 3

CriticalImpact
CriticalImpact

Reputation: 690

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

Upvotes: 4

Thomas Kelley
Thomas Kelley

Reputation: 10292

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)

Upvotes: 4

gremo
gremo

Reputation: 48899

I think you can simply do:

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

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

Upvotes: 11

Related Questions