Code Snippets

Using Ajax in Forms

The best way to refresh only part of a page on a specific event, use Ajax. Drupal provides an Ajax framework that allows you to partly update a page’s HTML. It is commonly used in forms. For more information regarding this topic, check the blog post!

Here is an example of using Ajax in a custom form:

function example_form($form, &$form_state) {
  $form = array();
  $form['selection'] = array(
    '#type' => 'select',
    '#title' => t('Selection'),
    '#options' => array(
      'selection1' => 'Selection 1',
      'selection2' => 'Selection 2',
      'selection3' => 'Selection 3',
    ),
    '#empty_value' => '',
    '#ajax' => array(
      'callback' => 'example_selection_callback',
      'wrapper' => 'message_id',
     ),
  );

  $form['message'] = array(
    '#type' => 'item',
    '#markup' => t('You have not made a selection yet.'),
  );

  return $form;
}

The function example_selection_callback is invoked when the selection of the element $form[‘selection’] is changed and would replace the element $form[‘message’] which contains the ID ‘message_id’.

function example_selection_callback($form, &$form_state) {
  $ajax = array(
    '#type' => 'ajax',
    '#commands' => array(),
  );

  $message = !empty($form_state['values']['selection']) ? t("I choose") . ' ' . $form_state['values']['selection'] : t('You have not made a selection.');

  $ajax['#commands'][] = ajax_command_html('#message_id', $message);

  return $ajax;
} 

This is the function callback for the form element ‘selection’. Whenever the selection is changed, the form element ‘message’ would be updated with the appropriate message. Notice that Ajax helper functions are used in the commands array. In this example, ajax_command_html() is used in order to replace the HTML inside of #message_id without having to refresh the whole page. For a complete list of Ajax commands, please visit Ajax framework commands.

Resource Tags: