0

Drupal 7. I'm using a contrib module that has one user permission associated with it. Enabling the module assigns that permission to only the "Administratror" role. I'd like to find a way of using a custom module to also assign the permission to a custom role I've created.

So far, I have within my custom module a function that runs when the contrib module is enabled.

function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module' => TRUE,
      ));
    }
  }
}

But it results in an error like this (output from Drush):

WD php: PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 role_permission.module may not be NULL: INSERT INTO {role_permission} (rid, permission, [error] module) VALUES (?, ?, ?); Array ( [0] => 5 [1] => 1 [2] => ) in user_role_grant_permissions() (line 3076 of /var/www/d7/modules/user/user.module). PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 role_permission.module may not be NULL: INSERT INTO {role_permission} (rid, permission, module) VALUES (?, ?, ?); Array ( [0] => 5 [1] => 1 [2] => ) in user_role_grant_permissions() (line 3076 of /var/www/d7/modules/user/user.module). Drush command terminated abnormally due to an unrecoverable error.
[error]

Looking at the table structure that third value [2] that's blank is supposed to be the name of the contrib module associated with the permission.

I think the problem is something along the lines of either the permission doesn't exist yet at that point in the execution, or maybe it's a security safeguard that prevents custom code from assigning permissions associated with separate modules. Either way I'd appreciate someone pointing me in the right direction with this.

  • Any reason not to simply click it via UI? – Mołot Jun 18 '13 at 23:07
2

There are hooks* to revoke or change permissions so there is no need to set TRUE or FALSE in your snippet.

Try this:

function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module',
      ));
    }
  }
}

In this call, you are setting the array's value to the permission name -- Not the key.

*: user_role_change_permissions() and user_role_revoke_permissions()

  • This worked perfectly, thanks! Initially I was working with user_role_change_permissions() and switched to user_role_grant_permissions() without amending what was passed to it. – Mark G Jun 19 '13 at 13:40

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.