1

Drupal Version: 8.5.5

Need to assign permission to existing role during module installation: Am using below code in hook_install:

use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
function hook_install() {

 $permission = 'test permission';
    $tester_rid = RoleInterface::TESTER;

    if ('tester' == Role::load($tester_rid)) {
      $tester_role->grantPermission($permission);
      $tester_role->save();
    }
}

Above grant permission is not working. I have also tried with

user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
      'my custom permission',
    ));
user_role_grant_permissions(RoleInterface::TESTER, array(
      'my custom permission',
    ));

Above hook_install is not working.

Pls help

  • Hey hey, welcome back to Drupal Answers. Above information is not sufficient to let us help you. We don't provide a debugging service scanning through your code to find out what exactly you want. Please update your question and properly explain what your are trying to do and why. – leymannx Aug 16 '18 at 10:19
  • 1
    Entity::load return an entity, not a string. You can't compare it with a string and expect a useful result – Clive Aug 16 '18 at 11:38
1

Try this:

use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;

function mymodule_install() {
  $role_object = Role::load('my custom role name');
  $role_object->grantPermission('my custom permission name');
  $role_object->save();
}

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.