1 form_example_tutorial.inc | form_example_tutorial_9($form, &$form_state) |
This is Example 9: a form with new fields dynamically added.
This example adds default values so that when the form is rebuilt, the form will by default have the previously-entered values.
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
File
- modules/
examples/ form_example/ form_example_tutorial.inc, line 543 - This is the form API tutorial.
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;
}