18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Drupal</strong> Permissions and Security<br />

When our module is enabled, the settings for these two permissions will be changed<br />

for the anonymous user.<br />

The user_role_change_permissions() function is actually used<br />

by the form submit handler for the Permissions form. By abstracting<br />

this logic to a function, <strong>Drupal</strong> provides an easy API call for other<br />

modules. When building your modules, you should look for similar<br />

opportunities so that other developers can build off your code instead of<br />

re-implementing similar logic.<br />

Defining roles programmatically<br />

Just as with permissions, <strong>Drupal</strong> 7 allows roles to be set through a simple function<br />

call. The new user_role_save() and user_role_delete() functions provide the<br />

tools your module needs.<br />

The user_role_save() function merely adds a new named role to the {roles} table<br />

and assigns it a proper role id ($rid). The user_role_delete() function removes<br />

that role from the {roles} table, and also cleans out any associated permissions<br />

stored in the {role_permission} table and any user role assignments stored in<br />

the {users_roles} table.<br />

Let's say that your module allows users to moderate other user accounts. This is a<br />

powerful capability on a site, so your module automatically creates a new role that<br />

contains the proper permissions.<br />

As in our preceding example, we will use hook_enable() to create the new role.<br />

/**<br />

* Create a role for managing user accounts.<br />

*/<br />

function account_moderator_enable() {<br />

// Create the 'account moderator' role.<br />

user_role_save('account moderator');<br />

}<br />

After creating the role, we can also auto-assign a series of permissions:<br />

/**<br />

* Create a role for managing user accounts.<br />

*/<br />

function account_moderator_enable() {<br />

// Create the 'account moderator' role.<br />

user_role_save('account moderator');<br />

[ 228 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!