Symfony2:在FormBuilder中获取用户角色列表

Symfony2:在FormBuilder中获取用户角色列表

问题描述:

我正在创建一个用于创建用户的表单,我想在创建用户时将一个或多个角色分配给用户.

I'm making a form for user creation, and I want to give one or several roles to a user when I create him.

如何获取在security.yml中定义的角色列表?

How do I get the list of roles defined in security.yml?

此刻是我的表单生成器:

Here's my form builder at the moment:

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

}

和User.php

public function getRolesNames(){
    return array(
        "ADMIN" => "Administrateur",
        "ANIMATOR" => "Animateur",
        "USER" => "Utilisateur",        
    );
}

当然,此解决方案不起作用,因为roles被定义为数据库中的位图,因此无法创建choices列表.

Of course, this solution doesn't work, because roles is defined as a bitmap in the database, therefore the choices list cannot be created.

谢谢.

security.role_hierarchy.roles容器参数将角色层次结构保存为数组.您可以对其进行概括以获取已定义角色的列表.

security.role_hierarchy.roles container parameter holds the role hierarchy as an array. You can generalize it to get list of roles defined.