Symfony2: Getting the list of user roles in FormBuilder

前端 未结 10 1403
爱一瞬间的悲伤
爱一瞬间的悲伤 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:42

    In Symfony 3.3, you can create a RolesType.php as follows:

    roles = array_unique($roles);
      }
    
      public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'choices' => $this->roles,
            'attr' => array(
                'class' => 'form-control',
                'aria-hidden' => 'true',
                'ref' => 'input',
                'multiple' => '',
                'tabindex' => '-1'
            ),
            'required' => true,
            'multiple' => true,
            'empty_data' => null,
            'label_attr' => array(
                'class' => 'control-label'
            )
        ));
      }
    
      public function getParent() {
        return ChoiceType::class;
      }
    
    }
    

    Then add it to the form as follows:

    $builder->add('roles', RolesType::class,array(
              'label' => 'Roles'
          ));
    

    Important is that each role must also be contained, for example: ROLE_ADMIN: [ROLE_ADMIN, ROLE_USER]

提交回复
热议问题