You are here

function ahah_example_dropdown in Examples for Developers 6

Form builder function to create a form showing dependent dropdowns. The second dropdown has its values populated based on the first.

Parameters

$form_state:

$my_values:

1 string reference to 'ahah_example_dropdown'
ahah_example_menu in ahah_example/ahah_example.module
Implement hook_menu().

File

ahah_example/ahah_example_dependent_dropdown.inc, line 14
Show/hide textfields based on checkbox clicks.

Code

function ahah_example_dropdown(&$form_state, $my_values = array()) {
  $form = array();

  // get the list of options to populate the first dropdown
  $initial_options = _ahah_example_get_first_dropdown_options();
  $form['explanation'] = array(
    '#type' => 'markup',
    '#value' => '<div>' . t('This is an example of a properly degrading dynamic form. It will work correctly with or without AJAX enabled. However, it has to provide an extra hidden button to change the values in the dependent dropdown.') . '</div>',
  );

  // if we have a value for the first dropdown from $form_state['values'] we use
  // this both as the default value for the first dropdown and also as a
  // parameter to pass to the function that retrieves the options for the
  // second dropdown.
  $master_selection = !empty($form_state['values']['master_dropdown']) ? $form_state['values']['master_dropdown'] : t('Strings');
  $form['master_dropdown'] = array(
    '#type' => 'select',
    '#title' => 'Master Dropdown',
    '#options' => $initial_options,
    '#default_value' => $master_selection,
    '#ahah' => array(
      'path' => 'examples/ahah_example/dependent_dropdown/callback',
      'wrapper' => 'dependent-dropdown-wrapper',
    ),
    '#attributes' => array(
      'class' => 'master-dropdown',
    ),
  );

  // The CSS for this module hides this next button if JS is enabled.
  $form['continue_to_dependent_dropdown'] = array(
    '#type' => 'submit',
    '#value' => t('Choose'),
    '#attributes' => array(
      'class' => 'next-button',
    ),
    '#submit' => array(
      'ahah_example_dropdown_continue',
    ),
  );
  $form['dependent_dropdown_holder'] = array(
    '#tree' => TRUE,
    '#prefix' => '<div id="dependent-dropdown-wrapper">',
    '#suffix' => '</div>',
  );
  $form['dependent_dropdown_holder']['dependent_dropdown'] = array(
    '#type' => 'select',
    '#title' => t('Dependent Dropdown (changes based on master dropdown)'),
    // when the form is rebuilt during processing (either AJAX or multistep),
    // the $master_selction variable will now have the new value and so the
    // options will change.
    '#options' => _ahah_example_get_second_dropdown_options($master_selection),
    '#default_value' => isset($my_values['dependent_dropdown']) ? $my_values['dependent_dropdown'] : '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
}