Symfony2: Set label of checkbox from Class Field Symfony2: Set label of checkbox from Class Field symfony symfony

Symfony2: Set label of checkbox from Class Field


There is good documentation in Symfony on how to do this - what you want to do is modify the form based on the underlying data. What you'll do is add a form event on PRE_SET_DATA, which is used with the starting data. Your buildForm() function would now look like this:

use Symfony\Component\Form\FormEvent;use Symfony\Component\Form\FormEvents;public function buildForm(FormBuilderInterface $builder, array $options){    $builder        ->add('id')        ->add('name')    ;    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {        $entity = $event->getData();        $form = $event->getForm();        // set default label if there is no data, otherwise use the name        $label = (!$entity || null === $entity ->getId())            ? 'Default'            : $entity->getName()        ;        $form->add('is_checked', 'checkbox', array(            'required' => false,            'label' => $label,        ));    });}

Another way would be to just pass the entity data to your template and manually set the label there, but the above solution is the more conventional way.