Symfony2: Getting the list of user roles in FormBuilder

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

    This is not exactly what you want but it makes your example working:

    use Vendor\myBundle\Entity\User;
    
    public function buildForm(FormBuilder $builder, array $options)
    {
        parent::buildForm($builder, $options);
    
        // add your custom fields
        $user = new User();
        $builder->add('regionUser');
        $builder->add('roles' ,'choice' ,array('choices' => User::getRolesNames(),
                'required'  => true,
        ));
    }
    

    But regarding getting your Roles from an entity, maybe you can use entity repository stuff to query the database.

    Here is a good example to get what to want using the queryBuilder into the entity repository:

    public function buildForm(FormBuilder $builder, array $options)
    {
        parent::buildForm($builder, $options);
    
        // add your custom fields
        $user = new User();
        $builder->add('regionUser');
        $builder->add('roles' ,'entity' array(
                     'class'=>'Vendor\MyBundle\Entity\User',
                     'property'=>'roles',
                     'query_builder' => function (\Vendor\MyBundle\Entity\UserRepository $repository)
                     {
                         return $repository->createQueryBuilder('s')
                                ->add('orderBy', 's.sort_order ASC');
                     }
                    )
              );
    }
    

    http://inchoo.net/tools-frameworks/symfony2-entity-field-type/

提交回复
热议问题