Symfony2 - How to put label and input for checkboxes/radios in a same line?

Viewed 42711

In my form I have some checkboxes, but by default, I have :

  • the first radio widget
  • the first label
  • the second radio widget
  • the label

Here is the html code generated by SYmfony2 :

  <div>
    <input ...>
    <label ...></label>
    <input ...>
    <label ...></label>
  </div>

What I want is to have :

the first radio widget the first label
the second radio widget the second label

The html code would be :

  <label .....><input ....></label>

I think I have to override the choice_widget but don't know how to put input and label on the same line

Here is the choice_widget I may need to override :

    {% block choice_widget %}
        {% spaceless %}
            {% if expanded %}
                <div {{ block('widget_container_attributes') }}>
                   {% for child in form %}
                      {{ form_widget(child) }}  {{ form_label(child) }}
                   {% endfor %}
                </div>
            {% else %}
                <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
                {% if empty_value is not none %}
                     <option value="">{{ empty_value|trans }}</option>
                {% endif %}
                {% if preferred_choices|length > 0 %}
                    {% set options = preferred_choices %}
                    {{ block('widget_choice_options') }}
                        {% if choices|length > 0 and separator is not none %}
                            <option disabled="disabled">{{ separator }}</option>
                       {% endif %}
                {% endif %}
                {% set options = choices %}
                {{ block('widget_choice_options') }}
                </select>
           {% endif %}
      {% endspaceless %}
   {% endblock choice_widget %}
9 Answers

In Symfony 3+, you can simply pass the radio-inline class to your form via label_attr:

$builder->add('type', ChoiceType::class, [
    'expanded' => true, 
    'label_attr' => ['class' => 'radio-inline']
]);

No need to create custom widgets or so...

you can guess those things by looking at the bootstrap_4_layout.html.twig offered by Symfony in your vendor directory (src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig)

Hope this helps.

Related