I'm making a form for user creation, and I want to give one or several roles to a user when I create him.
How do I get the list of roles defined in security.yml
?
Here's my form builder at the moment:
public function buildForm(FormBuilder $builder, array $options)
{
parent::buildForm($builder, $options);
// add your custom fields
$user = new User();
$builder->add('regionUser');
$builder->add('roles' ,'choice' ,array('choices' => $user->getRolesNames(),
'required' => true,
));
}
and in User.php
public function getRolesNames(){
return array(
"ADMIN" => "Administrateur",
"ANIMATOR" => "Animateur",
"USER" => "Utilisateur",
);
}
Of course, this solution doesn't work, because roles
is defined as a bitmap in the database, therefore the choices
list cannot be created.
Thanks in advance.
For a correct representation of your roles, you need recursion. Roles can extend other roles.
I use for the example the folowing roles in security.yml:
You can get this roles with:
An example with recursion:
The output:
This is so far the best way i found to get or set what i want from config files.
Bon courage
You can make a service for this and inject the "security.role_hierarchy.roles" parameter.
Service definition:
Service Class:
You can get the roles in your controller like this:
In Symfony 3.3, you can create a RolesType.php as follows:
Then add it to the form as follows:
Important is that each role must also be contained, for example: ROLE_ADMIN: [ROLE_ADMIN, ROLE_USER]