form_example_tutorial_9

6 form_example_tutorial.inc form_example_tutorial_9(&$form_state)
7 form_example_tutorial.inc form_example_tutorial_9($form, &$form_state)
8 form_example_tutorial.inc form_example_tutorial_9($form, &$form_state)

Example 9: A form with a dynamically added new fields.

This example adds default values so that when the form is rebuilt, the form will by default have the previously-entered values.

From handbook page http://drupal.org/node/717746.

See also

form_example_tutorial_9_add_name()

form_example_tutorial_9_remove_name()

form_example_tutorial_9_submit()

form_example_tutorial_9_validate()

Related topics

1 string reference to 'form_example_tutorial_9'

File

form_example/form_example_tutorial.inc, line 553
This is the Form API Tutorial from the handbook.

Code

function form_example_tutorial_9($form, &$form_state) {

  // We will have many fields with the same name, so we need to be able to
  // access the form hierarchically.
  $form['#tree'] = TRUE;

  $form['description'] = array(
    '#type' => 'item', 
    '#title' => t('A form with dynamically added new fields'),
  );

  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }

  // Build the number of name fieldsets indicated by $form_state['num_names']
  for ($i = 1; $i <= $form_state['num_names']; $i++) {
    $form['name'][$i] = array(
      '#type' => 'fieldset', 
      '#title' => t('Name #@num', array('@num' => $i)), 
      '#collapsible' => TRUE, 
      '#collapsed' => FALSE,
    );

    $form['name'][$i]['first'] = array(
      '#type' => 'textfield', 
      '#title' => t('First name'), 
      '#description' => t("Enter first name."), 
      '#size' => 20, 
      '#maxlength' => 20, 
      '#required' => TRUE,
    );
    $form['name'][$i]['last'] = array(
      '#type' => 'textfield', 
      '#title' => t('Enter Last name'), 
      '#required' => TRUE,
    );
    $form['name'][$i]['year_of_birth'] = array(
      '#type' => 'textfield', 
      '#title' => t("Year of birth"), 
      '#description' => t('Format is "YYYY"'),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit', 
    '#value' => 'Submit',
  );

  // Adds "Add another name" button
  $form['add_name'] = array(
    '#type' => 'submit', 
    '#value' => t('Add another name'), 
    '#submit' => array('form_example_tutorial_9_add_name'),
  );

  // If we have more than one name, this button allows removal of the
  // last name.
  if ($form_state['num_names'] > 1) {
    $form['remove_name'] = array(
      '#type' => 'submit', 
      '#value' => t('Remove latest name'), 
      '#submit' => array('form_example_tutorial_9_remove_name'),
      // Since we are removing a name, don't validate until later. 
      '#limit_validation_errors' => array(),
    );
  }

  return $form;
}
Login or register to post comments