Search code examples
phpformsclasssymfony

How do you hide labels in a form class in symfony2?


I know that you can split a form out in twig and choose to not render the label for a particular field, but I can't help but think that you must be able to do this from the form class. The 'label' key in the options array lets you change this value to whatever you like, but passing either false or an empty string just returns the field name (see examples below where 'roles' is rendered as the label).

$builder
            ->add('roles', 'entity', array(
                'class' => 'Acme\UserBundle\Entity\Role',
                'label' => '' 
            ));

$builder
            ->add('roles', 'entity', array(
                'class' => 'Acme\UserBundle\Entity\Role',
                'label' => false 
            ));

Strangely, passing an empty space (which feels very dirty) seems to render a completely empty label, with no space even when viewing the source. Can anyone shed any light on the best approach, or even why the empty space seems to work?


Solution

  • Since Symfony 2.2 you can avoid the <label> rendering using the false value for the label attribute:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Name', null, array('label' => false))
        ;
    }
    

    Source