2

In Drupal 7, I'm trying to grant a permission to a user role using hook_install and it doesn't work. But it works with hook_enable. Do you know how to make it work with hook_install as well?

function porta_batch_editor_install() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions); 
  }
}

It works with the following approach:

function porta_batch_editor_enable() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions); 
  }
}
1
  • I believe it didnt work with hook_install because I was disabling and re-enabling the module, when I uninstalled and enabled it, it worked(on my dev site). So, afaik, re-enabling a module doesnt trigger hook_install.
    – seb_dom
    May 9 '17 at 5:55
0

It should work on install. Are you actually uninstalling the module? Disabling and uninstalling is not the same thing in Drupal 7. Uninstall at admin/modules/uninstall, once the module is disabled. You can use drush pm-disable/pm-uninstall module_name.

  • test.module

    function test_permission() {
      return array(
        'test permission' => array(
          'title' => t('Test permission title'),
        ),
      );
    }
    
  • test.install

    function test_install() {
      $test_perm = array('test permission');
    
      $perms = module_invoke_all('permission');
      // We can find the 'test permission' in $perms.
    
      $role = user_role_load_by_name('administrator');
      user_role_grant_permissions($role->rid, $test_perm);
    }
    

The above gives administrators the test permission on module install.

0

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.