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.

The callback function hello_world_simple_form_callback() passes the<br />

$form and $form_state variables after they have gone through hello_world_<br />

simple_form_example(). In this case we are returning the form element that is<br />

being replaced.<br />

<strong>Drupal</strong> knows this is a renderable array and renders it to the appropriate value.<br />

<strong>Drupal</strong> sends the updated HTML back to the page where the <strong>Drupal</strong> AJAX<br />

handlers retrieve the changes and replace the wrapper.<br />

Chapter 10<br />

AJAX automatically applied<br />

AJAX can be automatically applied to elements on a page. This is done by applying<br />

the use-ajax class to an element on a page. A typical use would be to apply the<br />

use-ajax class to a link within a page to trigger an AJAX action. Links are<br />

commonly used because the page the link points to might be for the cases when<br />

JavaScript is disabled as a fallback.<br />

In the following example we are going to provide a link that, when clicked, will add<br />

"Hello World" to a div within the page. To start, we have two menu callbacks that<br />

we add to hello_world_menu(). One item for the page we are generating and the<br />

other is the callback URL used for AJAX or when JavaScript is disabled.<br />

$items['hello_world/link'] = array(<br />

'title' => 'Hello World: Link',<br />

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

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

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

);<br />

$items['hello_world_link_callback'] = array(<br />

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

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

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

);<br />

The first menu item is to our page where the link is located and where the AJAX will<br />

add content. The second menu item is the callback that will handle the AJAX request<br />

or the page request, when JavaScript is unavailable.<br />

function hello_world_link() {<br />

drupal_add_js('misc/ajax.js');<br />

$link = l(t('Say Hello'), 'hello_world_link_callback/nojs/',<br />

array('attributes' => array('class' => array('use-ajax'))));<br />

return '' . $link . '';<br />

}<br />

[ 307 ]

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

Saved successfully!

Ooh no, something went wrong!