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

强颜欢笑 提交于 2019-12-10 12:44:21

问题


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.


回答1:


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




回答2:


I think you can simply do:

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

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




回答3:


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)




回答4:


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


来源:https://stackoverflow.com/questions/10770707/how-can-i-add-css-classes-to-specific-symfony2-form-choices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!