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.

JavaScript in <strong>Drupal</strong><br />

t('Los Angelas') => t('Los Angelas'),<br />

),<br />

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

'callback' => 'hello_world_simple_form_callback',<br />

'wrapper' => 'ajax_markup_div',<br />

),<br />

);<br />

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

'#prefix' => '',<br />

'#suffix' => '',<br />

'#markup' => t('Hello World'),<br />

);<br />

if (!empty($form_state['values']['hello_city'])) {<br />

$form['ajax_markup']['#markup'] = t("Hello !city", array('!city'<br />

=> $form_state['values']['hello_city']));<br />

}<br />

return $form;<br />

}<br />

Here we have two form elements of hello_city and ajax_markup. The hello_city<br />

element has a #ajax property, which is new to <strong>Drupal</strong> 7. It defines a callback, which<br />

is an internal <strong>Drupal</strong> callback function, and a wrapper. This is the wrapper on the<br />

page that will be updated by the response to the AJAX request.<br />

The second element, called ajax_markup, is a markup form element. This element<br />

holds HTML. We initially populate the markup with 'Hello World'. For this element<br />

to be updated we need to add a wrapper to it. In this case the wrapper is a div with<br />

the same ID that we set as the wrapper in the #ajax part of the hello_city element.<br />

After the form is set up there is an if statement for the case when a value is available<br />

on $form_state for the hello_city element. When the form is initially created,<br />

there won't be a value. When the AJAX request is made, it will be passed through<br />

this form with the values from the form. When that happens the if statement will<br />

be executed causing the ajax_markup element to be updated.<br />

This will be followed by the execution of the callback defined by the #ajax property<br />

on the hello_world element. That function looks like this:<br />

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

return $form['ajax_markup'];<br />

}<br />

[ 306 ]

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

Saved successfully!

Ooh no, something went wrong!