[英]How to add classes to Symfony 4 "ChoiceType" item labels?
I have here four radio buttons, and I want to add a css class to each label of the radio button.我这里有四个单选按钮,我想为单选按钮的每个标签添加一个 css 类。 How can I do that?
我怎样才能做到这一点? I have tried two ways but neither are working:
我尝试了两种方法,但都没有用:
Try 1:尝试 1:
->add('background', ChoiceType::class, ['label'=>'2. Dein Hintergrund: ', //this adds class to the parent div 'attr' => ['class' => 'label'], 'choices' => [ 1 => 1, 2 => 2, 3 => 3, 4 => 4 ], 'choice_value' => null, 'expanded' => true, 'multiple' => false, // this adds class to all radios/input elements 'choice_attr' => function($choice, $key, $value){ return ['class' => 'radio radio_'.($key)]; }, //this does NOT work, no error but it will not render a class to the label? Why, 'label_attr' => function($choice, $key. $value){ return ['class' => 'label';($key)], }, ])
Try 2:尝试 2:
<div class="container"> {{ form_label(form.background, {'attr': {'class': 'label'}}) }} {{ form_widget(form.background) }} <button class="button_main">Übernehmen</button> </div>
With number 2 I get the following error:对于数字 2,我收到以下错误:
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").
在呈现模板期间抛出异常(“注意:数组到字符串的转换”)。
I have looked at this documentation many times but can't figure it out!我已经多次查看此文档,但无法弄清楚!
You need to make your own implementation of the template:您需要自己实现模板:
<div class="col-12">
{{ form_label(form.expandedField) }}
{% for child in form.expandedField.children %}
<div class="group-15">
<div class="custom-control custom-checkbox custom-checkbox-primary">
{{ form_widget(child, {'attr': {'class': 'custom-control-input'}}) }}
<label class="custom-control-label" for="{{ child.vars.id }}" >{{ child.vars.label }}</label>
</div>
</div>
{% endfor %}
</div>
Is not possible to add your own class to labels in FormTypes.无法将您自己的类添加到 FormTypes 中的标签。
You need to create your own form template like in this documentation您需要像本文档中那样创建自己的表单模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.