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.

Chapter 8<br />

The preceding code checks if the user editing a page may add a link to that page in<br />

the site's navigation menu. The permission administer menu indicates that the user's<br />

role is trusted enough to make structural changes to the site (for instance, like adding<br />

a link to this content on the Main menu, which appears on every page). The<br />

user_access() function returns a Boolean value, namely, if TRUE, the user may<br />

perform the requested action; if FALSE, the user may not. In the case of this form<br />

code, the form element will only be displayed if the access check returns TRUE.<br />

Otherwise, the form's default value will be retained.<br />

Note that the preceding example does not pass an $account object. As a result, the<br />

user_access() function defaults to using the current $user object, that is, the user<br />

currently making the page request. The $user object is stored in a global variable,<br />

and so it can be accessed any time a specific $account is not specified.<br />

You are not required to specify an $account when calling user_access(), and in<br />

most cases this is fine, but there are use cases where you might want to check the<br />

permission against a user other than the current logged-in $user.<br />

Checking the proper user account<br />

In most cases, permission checks are made against the current user, defined in the<br />

$user object. <strong>Module</strong> authors must pay careful attention to the context of their<br />

permission checks, especially when displaying information about specific users.<br />

For example, you may wish to add a section to the user account page where a site<br />

administrator can check the roles that an individual user has. To do this we would<br />

implement hook_user_view() and test the global $user object to ensure that this is<br />

a trusted administrator, who can view this information.<br />

First, we set up a simple check for the current user: Does he/she have the permission<br />

to view this information?<br />

function example_user_view($account, $view_mode) {<br />

if (!user_access('view user roles')) {<br />

return;<br />

}<br />

}<br />

You will see this pattern frequently in <strong>Drupal</strong> code. Failing the access check leads<br />

to a return out of the function and makes the code easier to follow. Since we are<br />

only adding information to an existing page, returning no data is fine. (Later in the<br />

chapter, we will look at other ways to deal with denied permissions.)<br />

[ 213 ]

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

Saved successfully!

Ooh no, something went wrong!