Customizing Form layout in Symfony

While working on a recent Symfony project I needed to modify the default Symfony form layout. In my case I needed to add a custom CSS class to the form.

Note: the tips below assume you are using the Twig layout engine.

1) Create a file to contain your overrides called app/resources/form/fields.html.twig.

2) Open up the base file

3) Copy the required blocks from the base file to your new fields.html.twig file an modify as needed.

4) In the forms that you want to use your new layout, add the following:
{% form_theme delete_form ‘form/fields.html.twig’ %}
where delete_form is the name of the form variable in the twig file.

Examples:

a) Add a class to the form (paste the following into your fields.html.twig file):

# line 270 in base file
{%- block form_start -%}
    {% set method = method|upper %}
    {%- if method in ["GET", "POST"] -%}
        {% set form_method = method %}
    {%- else -%}
        {% set form_method = "POST" %}
    {%- endif -%}
    <form name="{{ name }}" method="{{ form_method|lower }}"
{% if action != '' %} action="{{ action }}"{% endif %}
{% for attrname, attrvalue in attr %} {{ attrname }}="{{ attrvalue }}"
{% endfor %}{% if multipart %} enctype="multipart/form-data"{% endif %} 
class="form-class-name">
    {%- if form_method != method -%}
        <input type="hidden" name="_method" value="{{ method }}" />
    {%- endif -%}
{%- endblock form_start -%}

b) Add class to basic text fields:

{%- block form_widget_simple -%}
    {%- set type = type|default('text') -%}
    <input type="{{ type }}" class="input-class-name" {{ block('widget_attributes') }} 
{% if value is not empty %}value="{{ value }}" 
{% endif %}/>
{%- endblock form_widget_simple -%}

Symfony Docs here: http://symfony.com/doc/current/book/forms.html#global-form-theming