如何在 Symfony 生成的表单上将 CSS class 添加到 <select> 元素?

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

我正在测试 FormBuilder。当我生成一个 <select> 字段时,我不知道如何将 CSS class 添加到这个 HTML 元素:Symfony adds the class to the parent <div>.

这是我的 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',
                    ],
                ],
            ])
        // (...)
    }
}

这是 HTML 效果图:

<div id="user_roles" class="MyClass">
    <div>
        <label class="form-label required" 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>

这是我想要得到的 HTML 效果图:

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

我也试过从 Twig 模板修改 class,但结果是一样的。

有没有办法使用 FormBuilder 将此 class 分配给 <select>

要将 class 添加到 select,请将 attr 数组移动到 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',
            ],
        ],
    ])
// (...)