Home > database >  How to add CSS class to <select> element on a Symfony generated form?
How to add CSS class to <select> element on a Symfony generated form?

Time:04-19

I'm testing the FormBuilder. When I generate a <select> field, I can't figure out how to add a CSS class to this HTML element: Symfony adds the class to the parent <div>.

Here is my FormBuilder Class :

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
        // (...)
        ->add('roles', CollectionType::class, [
                'attr' => ['class' => 'MyClass'],
                'entry_type'   => ChoiceType::class,
                'entry_options'  => [
                    'label' => 'Select a role',
                    'label_attr' => [
                        'class' => 'form-label'
                    ],
                    'choices' => [
                        'User' => 'ROLE_USER',
                        'Admin' => 'ROLE_ADMIN',
                    ],
                ],
            ])
        // (...)
    }
}

Here is the HTML rendering :

<div id="user_roles" >
    <div>
        <label  for="user_roles_0">Select a role</label>
        <select id="user_roles_0" name="user[roles][0]">
            <option value="ROLE_USER" selected="selected">User</option>
            <option value="ROLE_ADMIN">Admin</option>
        </select>
    </div>
</div>

Here is the HTML rendering I would like to get :

<div id="user_roles">
    <div>
        <label  for="user_roles_0">Select a role</label>
        <select id="user_roles_0" name="user[roles][0]" >
            <option value="ROLE_USER" selected="selected">User</option>
            <option value="ROLE_ADMIN">Admin</option>
        </select>
    </div>
</div>

I've also tried to modify the class from the Twig template, but the result is the same.

Is there a way to assign this class to the <select> using the FormBuilder?

CodePudding user response:

To add the class to the select, move the attr array to the entry_options:

$builder
// (...)
->add('roles', CollectionType::class, [
        'entry_type'   => ChoiceType::class,
        'entry_options'  => [
            'attr' => ['class' => 'MyClass'],
            'label' => 'Select a role',
            'label_attr' => [
                'class' => 'form-label'
            ],
            'choices' => [
                'User' => 'ROLE_USER',
                'Admin' => 'ROLE_ADMIN',
            ],
        ],
    ])
// (...)
  • Related