Home > Net >  Double listbox with CollectionType/ChoiceType for user roles
Double listbox with CollectionType/ChoiceType for user roles

Time:05-05

With Symfony 4, I don't have this problem : a simple form to choose or edit the role of an user with a listbox.

Since I start a new project with Symfony 5 (with same code) when I edit a user profile, I have a double listbox like this :

Form example

One part of the User FormType :

$roles = [User::USER_DEFAULT => 'Simple User',
            User::USER_ADMIN_APP => 'App. Admin',
            User::USER_ADMIN_PROJECT => 'Project Admin',
            User::USER_ADMIN => 'Administrator'];

$builder->add('username')
            ->add('roles', CollectionType::class, [
                'label' => 'Roles', 'required' => true, 'entry_type' => ChoiceType::class,
                'entry_options' => ['label' => false, 'choices' => array_flip($roles)],])
            ->add('password')
            ->add('email')
            ->add('save', SubmitType::class);

In the database, i have a classical json format for user roles

#[ORM\Column(type: 'json')]
private $roles = [];

Some data from the fixture, I've created :

Database

I have created a GitHub fresh example in this page : form-tests-with-CollectionType

I know, I miss something but what ?? Should I use Data Transformers or Mappers to have only one listbox choice ?

Thanks for your lights. ;)

Update from 2022-05-04 :

From my old SF4 project to a new SF5 project, the only one change for the Roles field is "Array" to "Json" in Doctrine :

//Migration file with "Json"
roles CLOB NOT NULL --(DC2Type:json)

//Migration file with "Array"
roles CLOB NOT NULL --(DC2Type:array)

Now, I have a new format in the database for Roles field with "Array" :

a:1:{i:0;s:14:"ROLE_ADMIN_APP";}

Before with "Json", with my mistake in the fixture "ROLE_USER" :

["ROLE_USER","ROLE_ADMIN_APP"]

And with this change, I have a single listbox with ONLY ONE CHOICE for a user :

<select id="user_roles_0" name="user[roles][0]">
   <option value="ROLE_USER">Simple User</option>
   <option value="ROLE_ADMIN_APP">App. Admin</option>
   <option value="ROLE_ADMIN_PROJECT" selected="selected">Project Admin</option>
   <option value="ROLE_ADMIN">Administrator</option>
</select>

Finally, I can create or edit a user with a CollectionType and ChoiceType with multiple roles...

Hope it help for future devs/noob like me ;)

Cheers !

CodePudding user response:

You can try this :

$roles = [
    'Super Admin' => 'ROLE_SUPER_ADMIN',
    'Admin' => 'ROLE_ADMIN',
    ...
];

$builder->add('roles', ChoiceType::class, [
    'label' => 'form.label.role',
    'choices' => $roles,
    'required' => true,
    'multiple' => true,
    'expanded' => false
]);

My key => value is reversed and I'm using the ChoiceType directly.

  • Related