2
votes

I am using Symfony 5, I want to have a "User Edit" page in administration, in which I will change User Roles, I want to have checkboxes to define which role assign to user, so for that, I need Collection Type with CheckboxType entry inside (if I am true), but for first I can't use user roles array as value for collection type

$builder
        ->add('roles', CollectionType::class, [
            'entry_type' => CheckboxType::class,
            'entry_options' => [
                'required' => false,
            ],
        ])

This throws error

Unable to transform value for property path "[0]": Expected a Boolean.

after that, I tried to use a model transformer to change the value, below is code how I did that

$builder->get('roles')
        ->addModelTransformer(new CallbackTransformer(
            function($rolesAsArray){
                $rolesAsArray = array_flip($rolesAsArray);
                foreach($rolesAsArray as &$role){
                    $role = true; // I also tried to set key instead of value - true
                }
                return $rolesAsArray;
            },
            function($rolesAsString){
                dump($rolesAsString);die;
            }
        ));

After this, I didn't get an error but I get the form with this look

screenshot of error

So I haven't any option to change labels, and even I am submitting a form with these fields it throws an error

Expected argument of type "array", "null" given at property path "roles".

I found a way to do this with Select Box, but I can't found any way to do it with Checkbox.

If you have any ideas tell me, please.

1

1 Answers

1
votes

You can use ChoiceType :

$builder->add('roles', ChoiceType::class, array(
                'label' => 'form.label.role',

                'choices' => User::ROLES,
                'choice_translation_domain' => 'user',
                'multiple'  => true,
                'expanded' => true,
                'required' => true,
                ));

In User entity:

const ROLES = array(
    'roles.admin' => 'ROLE_ADMIN',
    'roles.secretary' => 'ROLE_SECRETARY',
    'roles.user' => 'ROLE_USER'
);