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

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!