Symfony2: Getting the list of user roles in FormBuilder

Gabriel Theron picture Gabriel Theron · Jun 28, 2012 · Viewed 31.2k times · Source

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.

Answer

Mun Mun Das picture Mun Mun Das · Jun 28, 2012

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