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

前端 未结 4 1398
刺人心
刺人心 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:37

    The solution with $options array provided by webda2l does not work with Symfony 2.3. It gives me an error:

    The option "roles" do not exist.

    I found that we can pass parameters to the form type constructor.

    In your controller :

    $roles_choices = array();
    
    $roles = $this->container->getParameter('security.role_hierarchy.roles');
    
    # set roles array, displaying inherited roles between parentheses
    foreach ($roles as $role => $inherited_roles)
    {
        foreach ($inherited_roles as $id => $inherited_role)
        {
            if (! array_key_exists($inherited_role, $roles_choices))
            {
                $roles_choices[$inherited_role] = $inherited_role;
            }
        }
    
        if (! array_key_exists($role, $roles_choices))
        {
            $roles_choices[$role] = $role.' ('.
                implode(', ', $inherited_roles).')';
        }
    }
    
    # todo: set $role as the current role of the user
    
    $form = $this->createForm(
        new UserType(array(
            # pass $roles to the constructor
            'roles' => $roles_choices,
            'role' => $role
        )), $user);
    

    In UserType.php :

    class UserType extends AbstractType
    {
        private $roles;
        private $role;
    
        public function __construct($options = array())
        {
            # store roles
            $this->roles = $options['roles'];
            $this->role = $options['role'];
        }
        public function buildForm(FormBuilderInterface $builder,
            array $options)
        {
            // ...
            # use roles
            $builder->add('roles', 'choice', array(
                'choices' => $this->roles,
                'data' => $this->role,
            ));
            // ...
        }
    }
    

    I took the idea from Marcello Voc, thanks to him!

提交回复
热议问题