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()
->getStorage('taxonomy_vocabulary')
->loadMultiple();
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)) {
$anonymous_role->grantPermission($permission);
}
if ($authenticated_role = Role::load($authenticated_rid)) {
$authenticated_role->grantPermission($permission);
}
}
}
Where should I grant these permissions within my module?