Skip to content

Instantly share code, notes, and snippets.

@Glideh
Last active March 11, 2024 12:24
Show Gist options
  • Save Glideh/27edd82b6b953b0b431225de9796c697 to your computer and use it in GitHub Desktop.
Save Glideh/27edd82b6b953b0b431225de9796c697 to your computer and use it in GitHub Desktop.
This is an example of how one could create a custom type for roles to add in a User form
security:
roles_label: "Permissions"
roles:
ROLE_SUPER_ADMIN: "Super Admin"
ROLE_ADMIN: "Administration"
ROLE_MONITOR: "Monitoring"
ROLE_FLEET: "Gestion du parc"
ROLE_ADMIN_USER: "Gestion des utilisateurs"
# ...
<?php
namespace AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
class RolesType extends AbstractType
{
protected $reachableRoles;
protected $roleChoices;
private $transPrefix = 'security.roles.';
public function __construct(RoleHierarchy $roleHierarchy, AuthorizationChecker $authorizationChecker)
{
$superAdminRole = 'ROLE_SUPER_ADMIN';
$currentPermissions = array(new Role($superAdminRole));
$this->reachableRoles = $roleHierarchy->getReachableRoles($currentPermissions);
$this->roleChoices = $this->getRoleChoices();
if (!$authorizationChecker->isGranted($superAdminRole)) {
unset($this->roleChoices[$this->transPrefix.$superAdminRole]);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'label' => 'security.role_labels',
'choices' => $this->roleChoices,
'choice_translation_domain' => true,
'expanded' => true,
'multiple' => true,
));
}
private function getRoleChoices()
{
$roles = array();
/** @var Role $role**/
foreach ($this->reachableRoles as $role) {
$roles[$this->transPrefix.$role->getRole()] = $role->getRole();
}
return $roles;
}
public function getParent()
{
return ChoiceType::class;
}
}
security:
role_hierarchy:
ROLE_SUPER_ADMIN:
- ROLE_ADMIN_USER
- ROLE_ADMIN
- ROLE_MONITOR
- ROLE_FLEET
ROLE_ADMIN_USER:
- ROLE_ADMIN
# ...
services:
admin.form.user_roles_type:
class: AdminBundle\Form\RolesType
arguments: ['@security.role_hierarchy', '@security.authorization_checker']
tags:
- { name: form.type}
@Glideh
Copy link
Author

Glideh commented Dec 30, 2016

Here I'm simply removing the ROLE_SUPER_ADMIN for non super admin users but the selectable choices could be based on the granted roles.

@lordelph
Copy link

Thanks for sharing this 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment