How to add radio button in symfony form?

Member

by deron , in category: PHP Frameworks , 3 months ago

How to add radio button in symfony form?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 3 months ago

@deron 

To add a radio button in a Symfony form, you can use the ChoiceType field type with the expanded option set to true.


Here's an example of adding a radio button in a Symfony form:

  1. Create a form class (e.g., MyFormType) extending AbstractType:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('my_radio', ChoiceType::class, [
                'choices' => [
                    'Option 1' => 'option1',
                    'Option 2' => 'option2',
                    'Option 3' => 'option3',
                ],
                'expanded' => true, // Render the choices as radio buttons
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => MyFormData::class,
        ]);
    }
}


  1. Create a data class to bind the form data (e.g., MyFormData):
1
2
3
4
5
class MyFormData
{
    public $my_radio;
    // ...
}


  1. In your controller, create a new instance of the form and handle the form submission:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;

class MyController extends AbstractController
{
    /**
     * @Route("/my-form", name="my_form")
     */
    public function myFormAction(Request $request)
    {
        $myFormData = new MyFormData();

        $form = $this->createForm(MyFormType::class, $myFormData);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Handle form submission and redirect
            // ...
        }

        return $this->render('my/template.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}


  1. Render the form in your template:
1
2
3
4
5
6
{# my/template.html.twig #}

<form method="POST" action="{{ path('my_form') }}">
    {{ form_widget(form) }}
    <button type="submit">Submit</button>
</form>


When you render the form, you will see radio buttons for each option defined in the choices option. The selected option will be stored in the my_radio property of the MyFormData class when the form is submitted.