Home > OS >  How to have radio buttons with Symfony?
How to have radio buttons with Symfony?

Time:09-21

In my search form, I want to make the choice of categories available with the selection of one of them, and only one of them. For now I have checkboxes instead of having radio buttons.

How do I get radio buttons instead of checkboxes?

SearchType.php

<?php

namespace App\Form;

use App\Entity\BigCity;
use App\Entity\Categories;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class SearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('bigcity', EntityType::class, [
                'class' => BigCity::class,
                'choice_label' => 'name',
                'placeholder' => 'Sélectionne une grande ville'
            ])
            ->add('category', EntityType::class, [
                'class' => Categories::class,
                'choice_label' => 'image',
                'expanded' => 'true',
                'multiple' => 'false',
            ])
            ->add('save', SubmitType::class)
        ;
    }

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

CodePudding user response:

For radio buttons use

            ->add('category', EntityType::class, [
                'class' => Categories::class,
                'choice_label' => 'image',
                'expanded' => true,
                'multiple' => false,
            ])

Also - be sure to use actual values (true not 'true' - a string)!

Doc is here

  • Related