31

I'm attempting to set the class on a class on a form label using php templates.

Here's my code:

<?php echo $view['form']->label($form['first_name'], 'First Name', array(
    'attr' => array('class' => 'control-label')
)) ?>

But here's my output:

<label class="required" for="form_first_name">First name</label>

I can find how to do it using twig, but not an example with PHP.

j0k
  • 22,600
  • 28
  • 79
  • 90
jeremib
  • 741
  • 2
  • 7
  • 17
  • On this page http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand you can see example of passing the class name into twig template, but you can choose to see the code in twig or in pure PHP. The thing is, the code is almost identical to yours so, I'm puzzled as you are. – Marko Jovanović Jul 25 '12 at 07:51
  • That's weird indeed as the code seems good to me ... have you modified the default form theme somewhere? which version of twig are you using? Have you tried to clean your application cache using `rm -rf`? – Geoffrey Brier Jul 25 '12 at 08:17

1 Answers1

72

I've got it...

<?php 
    echo $view['form']->label($form['first_name'], 'First Name', array(
            'label_attr' => array('class' => 'control-label'),
         )) 
?>

Apparently "attr" is "label_attr" for labels fields.

P.S. Corresponding twig code

{{ form_label(form.first_name, 'First Name', { 'label_attr': {'class': 'control-label'} }) }}
Marko Jovanović
  • 2,647
  • 3
  • 27
  • 36
  • 10
    for symfoy 2.1: `{{ form_label(form.item, label|default(null), { 'label_attr': { 'class': 'MYCLASS' } }) }}` – yogee Jan 28 '13 at 20:42
  • how can you merge this with existing labels ? – Sébastien Apr 29 '15 at 17:41
  • 2
    note for symfony 2.1: to keep original label (from the form class) use: `{{ form_label(form.item, null, { 'label_attr': { ... } }) }}` - note that `null` value – Jarda Jan 11 '16 at 22:49