How can I pass a full security roles list/hierarchy to a FormType class in Symfony2?

前端 未结 4 1400
刺人心
刺人心 2021-01-14 06:42

I have a user edit form where I would like to administer the roles assigned to a user.

Currently I have a multi-select list, but I have no way of populating it with

4条回答
  •  悲&欢浪女
    2021-01-14 07:39

    In your controller

    $editForm = $this->createForm(new UserType(), $entity, array('roles' => $this->container->getParameter('security.role_hierarchy.roles')));
    

    In UserType :

    $builder->add('roles', 'choice', array(
        'required' => true,
        'multiple' => true,
        'choices' => $this->refactorRoles($options['roles'])
    ))
    
    [...]
    
    public function getDefaultOptions()
    {
        return array(
            'roles' => null
        );
    }
    
    private function refactorRoles($originRoles)
    {
        $roles = array();
        $rolesAdded = array();
    
        // Add herited roles
        foreach ($originRoles as $roleParent => $rolesHerit) {
            $tmpRoles = array_values($rolesHerit);
            $rolesAdded = array_merge($rolesAdded, $tmpRoles);
            $roles[$roleParent] = array_combine($tmpRoles, $tmpRoles);
        }
        // Add missing superparent roles
        $rolesParent = array_keys($originRoles);
        foreach ($rolesParent as $roleParent) {
            if (!in_array($roleParent, $rolesAdded)) {
                $roles['-----'][$roleParent] = $roleParent;
            }
        }
    
        return $roles;
    }
    

提交回复
热议问题