Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Getting the list of user roles in 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.

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

}

and in User.php

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

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

Thanks in advance.

like image 642
Gabriel Theron Avatar asked Jun 28 '12 14:06

Gabriel Theron


1 Answers

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

like image 77
Mun Mun Das Avatar answered Sep 27 '22 20:09

Mun Mun Das