In my module, I am dynamically creating user permissions for vocabularies. I would like to also grant all roles the view permission, but I cannot figure out a proper way where to do it.

I cannot use a config yml, because these are dynamic permissions created within permission callback and both the hook_install and hook_modules_installed are run before the permission callback, so the roles don't pick up the permissions.

This is how I tried to grant the permissions in hook_install() and hook_modules_installed().

$vocabularies = \Drupal::entityTypeManager()

if (!empty($vocabularies)) {
  foreach ($vocabularies as $vocabulary) {
    $permission = 'view name defined in the callback ' . $vocabulary->id();
    $anonymous_rid = RoleInterface::ANONYMOUS_ID;
    $authenticated_rid = RoleInterface::AUTHENTICATED_ID;

    if ($anonymous_role = Role::load($anonymous_rid)) {
    if ($authenticated_role = Role::load($authenticated_rid)) {

Where should I grant these permissions within my module?


After granting the permissions, you should call the save() method to make the code work.

if ($anonymous_role = Role::load($anonymous_rid)) {
  • 1
    This works, thanks. I think i even had the save method called once, but it failed for some other reason i guess. But it seems to be a bit unlogical for me that i am able to grant the permissions to a role before they are even created, as both hooks run before the permission callback is called and the permissions are created.
    – Arend
    Dec 22 '17 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.