How to make radio button in symfony form?

Member

by mac , in category: PHP Frameworks , 9 months ago

How to make radio button in symfony form?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 9 months ago

@mac 

To create a radio button in a Symfony form, follow these steps:

  1. Define a field in your form class with the type ChoiceType:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use SymfonyComponentFormExtensionCoreTypeChoiceType;
// ...

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('color', ChoiceType::class, [
            'choices' => [
                'Red' => 'red',
                'Green' => 'green',
                'Blue' => 'blue',
            ],
            'expanded' => true, // to render as radio buttons
        ])
        // ...
    ;
}


In the example above, the field "color" is defined as a radio button group. The available choices are "Red", "Green", and "Blue".

  1. Render the form in your template:
1
2
3
{{ form_start(form) }}
    {{ form_widget(form.color) }}
{{ form_end(form) }}


  1. Handle the form submission in your controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use SymfonyComponentHttpFoundationRequest;
// ...

public function submitForm(Request $request)
{
    $form = $this->createForm(MyFormType::class);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        // ...
    }

    // ...
}


That's it! Now you should be able to see the radio button group in your form and handle the submitted data accordingly.