18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8<br />

If we had accidentally run the permission check on the $account object, then we<br />

might return the wrong permissions. For clarity, let's take a look at a more complex<br />

example. In the following snippet, we want to show a list of all content types that a<br />

user can create. Our function will begin much like the last implementation, and then<br />

get more complex.<br />

/**<br />

* Implement hook_user_view().<br />

*/<br />

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

if (!user_access('view content creation permissions')) {<br />

return;<br />

}<br />

// Get the defined node types.<br />

$node_types = node_permissions_get_configured_types();<br />

if (empty($node_types)) {<br />

return;<br />

}<br />

// Make an array for the list output.<br />

$list = array();<br />

foreach ($node_types as $type) {<br />

if (user_access('create ' . $type . ' content', $account)) {<br />

// Get the human-readable name of the content type.<br />

$list[] = check_plain(node_type_get_name($type));<br />

}<br />

}<br />

The preceding code snippet defines a function that pulls the permissions for<br />

the account being viewed by the current user. Our two sets of permission checks<br />

operate on different user accounts.<br />

The important piece here is the user_access() check that we run for each node<br />

type. If we were to leave off the $account, then this check would assume that we<br />

wanted to know what content types the current user could create. Doing so would<br />

mean the same results would appear no matter which user account page we viewed.<br />

Note: The use of the $account object instead of the $user object is<br />

a standard practice of <strong>Drupal</strong>, and a good coding practice. In <strong>Drupal</strong>,<br />

the $user object is a global value, and it would be a mistake to pass it<br />

(sometimes by reference!) when we only mean to extract information<br />

from it. Instead, lookup functions like hook_user_view() always act on<br />

a copy called $account. This pattern occurs frequently in <strong>Drupal</strong> core,<br />

and you should follow this best practice.<br />

[ 215 ]

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

Saved successfully!

Ooh no, something went wrong!