I have a user edit form where I would like to administer the roles assigned to a user.
Currently I have a multi-select list, but I have no way of populating it with
You can make your own type and then pass service container, from which you can then retrieve role hierarchy.
First, create your own type:
class PermissionType extends AbstractType
{
private $roles;
public function __construct(ContainerInterface $container)
{
$this->roles = $container->getParameter('security.role_hierarchy.roles');
}
public function getDefaultOptions(array $options)
{
return array(
'choices' => $this->roles,
);
);
public function getParent(array $options)
{
return 'choice';
}
public function getName()
{
return 'permission_choice';
}
}
Then you need to register your type as service and set parameters:
services:
form.type.permission:
class: MyNamespace\MyBundle\Form\Type\PermissionType
arguments:
- "@service_container"
tags:
- { name: form.type, alias: permission_choice }
Then during creation of form, simply add *permission_choice* field:
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('roles', 'permission_choice');
}
If you want to get only single list of roles without hierarchy, then you need to flat hierarchy somehow. One of possible solution is this:
class PermissionType extends AbstractType
{
private $roles;
public function __construct(ContainerInterface $container)
{
$roles = $container->getParameter('security.role_hierarchy.roles');
$this->roles = $this->flatArray($roles);
}
private function flatArray(array $data)
{
$result = array();
foreach ($data as $key => $value) {
if (substr($key, 0, 4) === 'ROLE') {
$result[$key] = $key;
}
if (is_array($value)) {
$tmpresult = $this->flatArray($value);
if (count($tmpresult) > 0) {
$result = array_merge($result, $tmpresult);
}
} else {
$result[$value] = $value;
}
}
return array_unique($result);
}
...
}