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.
security.role_hierarchy.roles
container parameter holds the role hierarchy as an array. You can generalize it to get list of roles defined.You can get a list of reachable roles from this method:
It seems to return all roles reachable from roles in array
$roles
parameter. It's an internal service of Symfony, whose ID issecurity.role_hierarchy
and is not public (you must explicitely pass it as parameters, it's not acessible from Service Container).In Symfony 2.7, in controllers you have to use $this->getParameters() to get roles :
If you need to get all inherited roles of certain role:
Then call this functon:
$this->getRoles('ROLE_ADMIN');
Here's what I've done:
FormType:
In the entity:
Please do provide feedback... I've used some suggestions from other answers, but I still feel like this is not the best solution!
This is not exactly what you want but it makes your example working:
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:
http://inchoo.net/tools-frameworks/symfony2-entity-field-type/