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

As a result, we cannot trust the menu callback to fire any action in<br />

example_ajax_add() without adding some additional security checks.<br />

First, we know that we need to check the user performing the action. From our<br />

earlier discussion, this is best handed through an access callback, so we edit<br />

our declaration:<br />

'access callback' => 'example_access_ajax_add',<br />

To run this check successfully, we also need to know the $user whose list is<br />

being updated:<br />

$items['example-ajax/%item/add/%user'] = array(<br />

We also need to pass the $user to our access callback:<br />

'access arguments' => array(3),<br />

So our rewritten hook looks like the following code:<br />

function example_menu() {<br />

$items = array();<br />

$items['example-ajax/%item/add/%user'] = array(<br />

'title' => 'Example AJAX add to list',<br />

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

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

'access callback' => 'example_access_ajax_add',<br />

'access arguments' => array(3),<br />

'type' => MENU_CALLBACK,<br />

);<br />

return $items;<br />

}<br />

In our access callback, we can now check that the link references the current user. So<br />

our HTML code will look something like the following:<br />

Add to my list<br />

The code to generate this link would run through <strong>Drupal</strong>'s l() function:<br />

if ($user->uid > 0) {<br />

$output = l(t('Add to my list'), 'example-ajax/'. $item->id .'/<br />

add/'. $user->uid);<br />

return $output;<br />

}<br />

[ 237 ]

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

Saved successfully!

Ooh no, something went wrong!