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.

Node Access<br />

Note that we do not have access to the $node object here. This is because the node<br />

access API is used to provide advanced filtering of queries, both for single nodes and<br />

for groups of nodes. This level of abstraction is what makes node access work.<br />

So our Role Access module must determine what permissions our current user has.<br />

This is a fairly simple operation, since user roles are attached to the $account object:<br />

/**<br />

* Implement hook_node_grants().<br />

*/<br />

function role_access_node_grants($account, $op) {<br />

// Get the user roles.<br />

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

}<br />

// Error checking.<br />

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

return array();<br />

}<br />

// Initialize a $grants array.<br />

$grants = array();<br />

// Iterate through the roles.<br />

foreach ($roles as $grant_id) {<br />

$grants['role_access'][] = $grant_id;<br />

}<br />

// Return the grants.<br />

return $grants;<br />

Again, we are expected to return a $grants array. This array is keyed by the realm(s)<br />

of our module. Each realm may then declare an array of grant ids.<br />

These values are then concatenated for all modules on the site, and a final $grants<br />

array is constructed. This array is used to alter queries to the {node} table in order<br />

to enforce our node access rules.<br />

These grants must match those provided in hook_node_access_records(),<br />

otherwise, the grants will fail and the operation will be denied.<br />

[ 270 ]

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

Saved successfully!

Ooh no, something went wrong!