Symfony FormType Choice | Set data default to group of radio button

Web developer Front-End in Oise, France - Gary Deshayes <--Traduction

Created at : Sunday 26 July 2020


How to set a default value to a ChoiceType radio button group under Symfony 4+?

Currently you probably use the forms this way:

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('choice', ChoiceType::class, [
             'label' => 'Choice',
             'choices' => [
                  'Yes' => 2,
                  'No' => 1,
                  "I dont' know" => 0
              ],
             'expanded' => true,
             'multiple' => false
     ]);
 }

This gives you as a result a group of 3 radio buttons with only one possible choice, but if you put directly here a default value, it will overwrite the values of the entity if you want to change it afterwards.

Set a default value in case of entity creation in the FormType

Instead of using the usual method as above, use this method from the official documentation that uses Form Events :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // We modify the form before defining the datas
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        //We retrieve the entity related to the form
        $entity = $event->getData();
        $form = $event->getForm();

        $form->add('choice', ChoiceType::class, [
             'label' => 'Choice',
             'choices' => [
                  'Yes' => 2,
                  'No' => 1,
                  "I don't know" => 0
              ],
             'expanded' => true,
             'multiple' => false
             //The default value is set here
             //If the choice exists we put it if not we put at 0 (I don't know)
             'data' => $entity->getChoice() ? $entity->getChoice() : 0
        ]);
    });
}

It allows you to define the right value according to the entity and thus always keep in mind the form according to the entity modified or not.

Thank you for reading, do not hesitate to share!

News publications :
Symfony

Created at : Monday 1 November 2021

Javascript Framework JS

Created at : Sunday 31 October 2021

Symfony

Created at : Wednesday 1 September 2021

Javascript Framework JS

Created at : Saturday 28 November 2020

Javascript SQL Framework JS

Created at : Sunday 20 September 2020

Symfony

Created at : Thursday 6 August 2020

Javascript jQuery

Created at : Monday 23 March 2020

Symfony

Created at : Friday 14 February 2020

Symfony Bugs

Created at : Sunday 26 January 2020