User login

Setting permissions for your module when it is enabled

Most recently i did this in the Drush script Scaffolding:

<?php
 
// See devel output when using site as Anonymous or authenticated user.
 
user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access devel information' => TRUE));
 
user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array('access devel information' => TRUE));
 
drush_print("\nSet permissions to allow anonymous and normal authenticated users to see Devel module debug output.");
?>

But of course it works in a module also, even if it is rarely done.

I am a little obsessed with making modules come with sensible defaults (see http://drupal.org/node/182023) but still i am surprised to not find a recommended way for modules to set permissions documented. I am going with user_role_grant_permissions() in a hook_enable().

/web/sites/all/modules/custom/feature_seo/feature_seo.module

<?php
/**
 * Implements hook_enable().
 *
 * Actually a callback run for just your module after it is enabled.  We use it
 * to set permissions for the page_title module required by feature_seo.
 */
function feature_seo_enable() {
 
$admin_role = user_role_load_by_name('content manager');
 
// Additional permissions.
 
user_role_grant_permissions($admin_role->rid, array(
   
'set page title' => TRUE,
   
'administer page titles' => TRUE,
  ));
}
?>

Note: I was actually trying to rely on a role created in an installation profile, and the installation profile's .install runs after all the module .install and the module enablings, so in this case i had to move the permissions-granting to the .install file. Presumably Features might have been able to handle this, but it may be that a role must be Drupal-core-hardcoded or provided by your own module for this to work nicely in a Feature-enabled-by-installation-profile situation. See my plea for default roles again.

See also: http://data.agaric.com/permission-sets-sensible-defaults-module-provided-permissions-roles

Searched words: 
set permissions for a new module drupal set default permissions programmatically grant permissions

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.