Symfony2: Getting the list of user roles in FormBuilder

前端 未结 10 1429
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 15:55

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

10条回答
  •  感动是毒
    2020-12-08 16:50

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

提交回复
热议问题