1 ajax_example.module ajax_example_simplest($form, &$form_state)

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 Reference

Related topics

File

modules/examples/ajax_example/ajax_example.module, line 295
Hook implementations for the AJAX Example module.

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',
      // There are also several optional keys - see ajax_example_autocheckboxes
// below for details on 'method', 'effect' and 'speed' and
// ajax_example_dependent_dropdown for 'event'.
    ),
  );

  // 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;
}