Symfony 5 – Select (or check box) for user roles in a form

For choosing between a html select or checkboxes on your form, just toggle the “multiple” parameter on the ChoiceType class. Since the roles are an array, we need a data transformer.



namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\CallbackTransformer;

class UserType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
            ->add('Roles', ChoiceType::class, [
                    'required' => true,
                    'multiple' => false,
                    'expanded' => false,
                    'choices'  => [
                      'User' => 'ROLE_USER',
                      'Partner' => 'ROLE_PARTNER',
                      'Admin' => 'ROLE_ADMIN',



        // Data transformer
            ->addModelTransformer(new CallbackTransformer(
                function ($rolesArray) {
                     // transform the array to a string
                     return count($rolesArray)? $rolesArray[0]: null;
                function ($rolesString) {
                     // transform the string back to an array
                     return [$rolesString];


    public function configureOptions(OptionsResolver $resolver)
            'data_class' => User::class,

3 thoughts on “Symfony 5 – Select (or check box) for user roles in a form”

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading Facebook Comments ...
Loading Disqus Comments ...