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

Declaring your own access functions<br />

The user_access() function is a great utility function, but it cannot cover all logical<br />

use cases. It cannot, for instance, check two access permissions at the same time. You<br />

can, of course, write a statement such as:<br />

if (user_access('permission one') && user_access('permission two')) {<br />

// perform some action…<br />

}<br />

When securing actions within your code, this approach is perfectly fine. However,<br />

menu-based access checks cannot be subject to such rules. In these cases, we need to<br />

declare our own access callback within the menu item.<br />

For instance, let's take our last module example. Suppose that instead of displaying<br />

this information on the user profile page, we wanted to make a stand-alone page for<br />

this information. We might make a tab on the user page, using a menu callback like<br />

the following one:<br />

/**<br />

* Implement hook_menu().<br />

*/<br />

function example_menu() {<br />

$items['user/%user/content'] = array(<br />

'title' => 'Content creation',<br />

'page callback' => 'example_user_page',<br />

'page arguments' => array(1),<br />

'access arguments' => array('view content creation permissions'),<br />

'type' => MENU_LOCAL_TASK,<br />

);<br />

return $items;<br />

}<br />

This would work just fine, unless we needed to check an additional permission or<br />

condition during the access check. Suppose our business rules say that only editors<br />

who may also administer users may view this page.<br />

In that case, we have a problem, because the user_access() function cannot accept<br />

multiple permissions during a single call. In this case, we have to use the access<br />

callback parameters of the menu $item:<br />

/**<br />

* Implement hook_menu().<br />

*/<br />

function example_menu()<br />

example_menu() {<br />

[ 221 ]

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

Saved successfully!

Ooh no, something went wrong!