How to add a css class on a "form_row" in twig template

My answer is very similar to nni6's but it allows you to pass through the entire attr array.

My HTML structure is for Twitter Bootstrap but you can have whatever you want. This example also places an error class on the wrapper div if there are any errors - this part is not required but is useful if you use Bootstrap:

{% extends 'form_div_layout.html.twig' %}

{% block field_row %}
{% spaceless %}
    {% set field_row_classes = ['control-group'] %}
    {% if errors|length > 0 %}
        {% set field_row_classes = field_row_classes|merge(['error']) %}    
    {% endif %}

    <div class="{{ field_row_classes|join(' ') }}">
        {{ form_label(form, label|default(null)) }}
        <div class="controls">
            {{ form_widget(form, { 'attr' : attr|default({}) }) }}
            {{ form_errors(form) }}
            {% if help is defined %}
                <p class="help-block">{{ help }}</p>
            {% endif %}
        </div>
    </div>
{% endspaceless %}
{% endblock field_row %}

The difference here is that I'm calling form_widget with the attr array (if it was specified, defaults to {})

Now you can set up your form as normal but pass through a custom class:

{{ form_row(myentity.myproperty, { 'label' : 'mylabel', 'attr' : { 'class' : 'myclass' }}) }}

This post need an update !

Since Symfony 4.3, the row_attr option permits to add attributes (and so, some class). Let's check those links :

  • Here : https://symfony.com/blog/new-in-symfony-4-3-more-form-improvements#row-attributes-in-form-themes

  • or more specifically : https://symfony.com/doc/current/reference/forms/types/form.html#row-attr


If you want the common class for the form_row (it means one class for form_label, form_widget and form_errors), you should customize a field_row block.

This article explains how to customize form fields: How to customize Form Rendering. There are some methods to do this.

For example I'm using Method 2 (How to customize Form Rendering: Method 2):

{% extends 'form_div_layout.html.twig' %}

{% block field_row %}
{% spaceless %}
    {% set class='' %}
    {% if attr.class is defined %}
    {% set class = 'class="' ~ attr.class ~ '"' %}
    {% endif %}

    <div {{ class }} >
        {{ form_label(form, label|default(null)) }}
        {{ form_errors(form) }}
        {{ form_widget(form) }}
    </div>
{% endspaceless %}
{% endblock field_row %}

Tags:

Twig

Symfony