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.

Chapter 10<br />

AJAX helpers<br />

Included in <strong>Drupal</strong> is an AJAX library that integrates <strong>Drupal</strong>, jQuery, and AJAX.<br />

This system provides a set of properties for forms and functions, to use in <strong>Drupal</strong><br />

callbacks, which quickly and easily build AJAX into <strong>Drupal</strong> modules. Using the<br />

helper functions and properties AJAX can be built into <strong>Drupal</strong> pages rather than<br />

bolted into the pages.<br />

Adding AJAX to forms<br />

A common use of AJAX is dynamically updating forms, based on input, to other<br />

parts of the form. When one element in the form is updated, other elements change<br />

or are populated with information based on a change. For an example, we can look<br />

at an option list form element that updates a markup element.<br />

We start with an implementation of hook_menu() to define the form page, as<br />

seen here:<br />

/**<br />

* Implements hook_menu().<br />

*/<br />

function hello_world_menu() {<br />

$items = array();<br />

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

'title' => 'Hello World: Simple AJAX Example',<br />

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

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

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

);<br />

}<br />

return $items;<br />

We follow this by creating a form callback called hello_world_simple_form_<br />

example(). This creates the form to insert into the page.<br />

function hello_world_simple_form_example($form, &$form_state) {<br />

$form = array();<br />

$form['hello_city'] = array(<br />

'#title' => t("Choose a city"),<br />

'#type' => 'select',<br />

'#options' => array(<br />

t('World') => t('World'),<br />

t('Chicago') => t('Chicago'),<br />

t('New York') => t('New York'),<br />

[ 305 ]

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

Saved successfully!

Ooh no, something went wrong!