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 9<br />

When hook_node_access_records() fires, it passes a single parameter, the $node<br />

object being acted upon. Our module must respond based on the information in the<br />

$node object or be able to derive its rules from that information.<br />

This last statement may seem obvious, but bears repeating. If<br />

your business rules rely on special information not found in the<br />

default $node object, it is your responsibility to add that data<br />

using hook_node_load(). We will look at this in more detail<br />

later in this chapter.<br />

For Role Access, we need to know the roles assigned to the user who authored<br />

the node.<br />

/**<br />

* Implement hook_node_access_records().<br />

*<br />

* We want to store a row for each role assigned<br />

* to the author of the content.<br />

*<br />

*/<br />

function role_access_node_access_records($node) {<br />

// First get the user record. Note that we avoid using $user here,<br />

// since that is the global $user object.<br />

$account = user_load($node->uid);<br />

// Now, get the roles array from the $account object.<br />

$roles = array_keys($account->roles);<br />

Here we use the <strong>Drupal</strong> API to grab the roles assigned to the node author. The use of<br />

array_keys() in the last line means that we will be given a simple array of role ids.<br />

These role ids will be used as the grant ids that we store in the {node_access} table.<br />

A typical $roles result will look like this if we var_dump() its value:<br />

array(2) {<br />

[0]=> int(2)<br />

[1]=> int(4)<br />

}<br />

[ 267 ]

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

Saved successfully!

Ooh no, something went wrong!