1 ajax_example_node_form_alter.inc ajax_example_form_node_form_alter(&$form, &$form_state, $form_id)

Implements hook_form_FORM_ID_alter().

Adds two fields to the node form, second only appears after first is enabled.

File

modules/examples/ajax_example/ajax_example_node_form_alter.inc, line 16
This example shows how to use AJAX when altering a node form.

Code

function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    ),
  );
  $form['container'] = array(
    '#prefix' => '<div id="ajax-example-form-node">',
    '#suffix' => '</div>',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
     || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ? $node->ajax_example['example_2'] : $form_state['values']['ajax_example_2'],
    );
  }
}