You are here

function ajax_example_simplest in Examples for Developers 7

Basic AJAX callback example.

Simple form whose ajax-enabled 'changethis' member causes a text change in the description of the 'replace_textfield' member.

See Form API Tutorial

Related topics

1 string reference to 'ajax_example_simplest'
ajax_example_menu in ajax_example/ajax_example.module
Implements hook_menu().

File

ajax_example/ajax_example.module, line 305
AJAX Examples module file with basic examples.

Code

function ajax_example_simplest($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#title' => t("Choose something and explain why"),
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element changes.
      'callback' => 'ajax_example_simplest_callback',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'replace_textfield_div',
    ),
  );

  // This entire form element will be replaced whenever 'changethis' is updated.
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("Why"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
  );

  // An AJAX request calls the form builder function for every change.
  // We can change how we build the form based on $form_state.
  if (!empty($form_state['values']['changethis'])) {
    $form['replace_textfield']['#description'] = t("Say why you chose '@value'", array(
      '@value' => $form_state['values']['changethis'],
    ));
  }
  return $form;
}