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.

Node Access<br />

This permission will inform our use of hook_node_access_records_alter().<br />

hook_node_access_records_alter() is almost identical to hook_node_access_<br />

records(). The function passes the &$grants array by reference, plus the $node<br />

being acted upon.<br />

/**<br />

* Implement hook_node_access_records_alter().<br />

*<br />

* If a user saves content, make sure that an access record for the<br />

* 'authenticated user' role should actually be stored.<br />

*/<br />

function role_access_extend_node_access_records_alter(&$grants, $node)<br />

{<br />

If we run a var_dump() on the typical $grants being passed to this function, we see<br />

an array that should seem familiar:<br />

array(2) {<br />

[0]=><br />

array(6) {<br />

["realm"]=> string(11) "role_access"<br />

["gid"]=> int(2)<br />

["grant_view"]=> int(1)<br />

["grant_update"]=> int(1)<br />

["grant_delete"]=> int(1)<br />

["priority"]=> int(0)<br />

}<br />

[1]=><br />

array(6) {<br />

["realm"]=> string(11) "role_access"<br />

["gid"]=> int(5)<br />

["grant_view"]=> int(1)<br />

["grant_update"]=> int(1)<br />

["grant_delete"]=> int(1)<br />

["priority"]=> int(0)<br />

}<br />

}<br />

What we need to do is make sure that the realm 'role_access' only returns grant id 2<br />

if the user's role allows it. So we run a check for the user's permissions and modify<br />

the $grants array as needed.<br />

// We cannot use the global $user here; we want the creator/editor<br />

of the content.<br />

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

[ 280 ]

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

Saved successfully!

Ooh no, something went wrong!