Search code examples
cssclassinputsymfonyformbuilder

Symfony2 - FormBuilder - add a class to the field and input


I want to add a class to certain input or label elements in a Symfony application.

I can do something like this in a form on the Twig level:

<div class="row">
    {{ form_label(form.subject) }}
    {{ form_widget(form.subject, { 'attr': {'class': 'c4'} }) }}
</div>

This works fine. But I have to setup and write out the whole template for every form manually. And I actually want to use:

{{ form_widget(form) }}

So, I was thinking, how could I add a CSS class for a label or an input somewhere in the FormType:

class SystemNotificationType extends AbstractType {
    public function buildForm(FormBuilder $builder, array $options) {
        $builder->add('subject', 'text', array(
            'label' => 'Subject'
        ));

I think this might be more useful, as you can configure the whole form in one place.

How can this be done? Maybe I'm thinking about it the wrong way.


Solution

  • The class of a field is part of the presentation layer of your application, so it is best to create a twig theme for your forms:

    Create a file fields.html.twig in Resources/views/Form of your Bundle and define how your form row will be formated, for example:

    {% block field_row %}
    <div class="row">
        {{ form_errors(form) }}
        {{ form_label(form) }}
        {{ form_widget(form, { 'attr': {'class': 'c4'} }) }}
    </div>
    {% endblock field_row %}
    

    If you want to customize only certain field, for example the field fieldName of the form formName, customize the row:

    {% block _formName_fieldName_row %}
    <div class="row">
        {{ form_label(form) }}
        {{ form_errors(form) }}
        {{ form_widget(form, { 'attr': {'class': 'c4'} }) }}
    </div>
    {% endblock %}
    

    EDIT: customize only the field:

    {% block _formName_fieldName_widget %}
        {% set type = type|default('text') %}
        <input type="{{ type }}" {{ block('widget_attributes') }} value="{{ value }}" class="c4" />
    {% endblock %}
    

    Then in all the form templates you want it use this theme add:

    {% form_theme form 'MyBundle:Form:fields.html.twig' %}
    

    This is explained in depth in the cookbook