Symfony2: Getting the list of user roles in FormBuilder Symfony2: Getting the list of user roles in FormBuilder symfony symfony

Symfony2: Getting the list of user roles in FormBuilder


security.role_hierarchy.roles container parameter holds the role hierarchy as an array. You can generalize it to get list of roles defined.


You can get a list of reachable roles from this method:

Symfony\Component\Security\Core\Role\RoleHierarchy::getReachableRoles(array $roles)

It seems to return all roles reachable from roles in array $roles parameter. It's an internal service of Symfony, whose ID is security.role_hierarchy and is not public (you must explicitely pass it as parameters, it's not acessible from Service Container).


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();