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

insertusernamehere picture insertusernamehere · Jun 14, 2012 · Viewed 54.1k times · Source

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.

Answer

Pappa picture Pappa · Jun 14, 2012

You can do it like this:

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