Symfony2, How to make a form label class/attr different than its input? Symfony2, How to make a form label class/attr different than its input? symfony symfony

Symfony2, How to make a form label class/attr different than its input?


As mentioned in the documentation:

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

You can set those attributes in twig template or in form builder:

Twig template:

  • for symfony 2.1 and newer use:

    {{ form_label(form.hours, null, {'label_attr': {'class': 'foo'}}) }}
  • in the legacy symfony 2.0 it used to be

    {{ form_label(form.hours, { 'label_attr': {'class': 'MYCLASSFOR_LABEL'} }) }}{{ form_widget(form.hours, { 'attr': {'class': 'MYCLASSFOR_INPUTS'} }) }}

Form builder

public function buildForm(FormBuilderInterface $builder, array $options){    $builder->add('hours', null, array(        'label_attr' => array('class' => 'MYCLASSFOR_LABEL'),        'attr'       => array('class' => 'MYCLASSFOR_INPUTS'),    ));}


This may be new, but there's an easy way to do this now:

$builder    ->add('hours', null , array(        'attr'=>             array(                'placeholder'=>'Working Hours',                'class'=>'MYCLASSFOR_INPUTS')         ) ,        'label_attr' => array(            'class' => 'MYCLASSFOR_LABEL'        )    );

The option you're looking for is label_attr.


This works for me in Symfony 2.3:

{{ form_row(form.hours,  {   'label': 'Hours:'                            ,'label_attr': {'class': 'MYCLASSFOR_LABEL'}                            ,'attr': {'class': 'MYCLASSFOR_INPUTS'}                         }           )}}