Search code examples
htmlcsssymfony4

Is it possible to add CSS class to form_row in twig Symfony 4?


I am trying to add a CSS class to the whole form_row in a twig template from Symfony 4! As you can see from the image, my code right now only adds the class to the input tag, put I need the class to be added to the parent div container.

Below is my code:

        {{ form_row(form.firstname, { 'attr' : {'class' : 'first_name'} }) }}

below is an image of the rendered code:

enter image description here


Solution

  • From the documentation of symfony:

    attr: A key-value array that will be rendered as HTML attributes on the field.

    This means the attributes only get applied to the field.

    You could instead wrap the whole div in another div like so:

    <div class='first-name'>
         {{ form_row(form.firstname) }}
    </div>
    

    And then apply the style either to div.first-name or div.first-name > div

    Alternatively: Render the whole row yourself

    With the following you can render the label and widget yourself:

    <div class='first-name'>
        {{ form_label(form.firstname) }}
        {{ form_widget(form.firstname) }}
    </div>