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.y
You can make a service for this and inject the "security.role_hierarchy.roles" parameter.
Service definition:
acme.user.roles:
class: Acme\DemoBundle\Model\RolesHelper
arguments: ['%security.role_hierarchy.roles%']
Service Class:
class RolesHelper
{
private $rolesHierarchy;
private $roles;
public function __construct($rolesHierarchy)
{
$this->rolesHierarchy = $rolesHierarchy;
}
public function getRoles()
{
if($this->roles) {
return $this->roles;
}
$roles = array();
array_walk_recursive($this->rolesHierarchy, function($val) use (&$roles) {
$roles[] = $val;
});
return $this->roles = array_unique($roles);
}
}
You can get the roles in your controller like this:
$roles = $this->get('acme.user.roles')->getRoles();