Search code examples
symfonycheckboxformbuilder

Symfony2: Set label of checkbox from Class Field


I have a Class with 3 fields:

$id, $name, $isChecked

I have a formtype and I want, that the label of the $id field is the $name field. Is that possible?

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('id')
        ->add('name')
        ->add('is_checked', 'checkbox', array(
            'required' => false,
            'label' => //This should be the $name field
        ))
    ;
}

For example I have my Class with $id = 1, $name= "Car". Then I want it like this:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('id')
        ->add('name')
        ->add('is_checked', 'checkbox', array(
            'required' => false,
            'label' => 'Car',
        ))
    ;
}

--> The "Car" word should be the $name Variable of my Class. Or how do I make my whole Class as a Checkbox in my Twig/Form? I only want, that I can check my Checkbox and I than know, ok "isChecked" is true and then I have the relation to my ID and my Name. But the user needs to know, which checkbox is which value, so I need the "name" as the label


Solution

  • 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.