@mac
To create a radio button in a Symfony form, follow these steps:
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 2 3 |
{{ form_start(form) }}
{{ form_widget(form.color) }}
{{ form_end(form) }}
|
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.