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

symfony, twig

Solution

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 %}

Problem

I would like to know how I can add a css class on a "{{ form_row() }}" in twig. For the moment, I have this code : ``` {{ form_row(form.username, {'label' : "Login", 'attr': {'class': 'loginForm'}}) }} ``` ... But the CSS class "loginForm" isn't used in the HTML code. Thank you :) !

Original source