I have here four radio buttons, and I want to add a css class to each label of the radio button. How can I do that? I have tried two ways but neither are working:
Try 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:
<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:
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.
You need to create your own form template like in this documentation
Apparently you can't modify the attributes of a choice label of ChoiceType. This feature does not exist in Symfony core for the moment. Please have a look to this .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.