I'm trying to add an "add more" field to a form in my custom module. I've been looking at the examples module, with no luck.
Here's what I have so far:
$form['#tree'] = TRUE;
$form['names_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('People coming to the picnic'),
// Set up the wrapper so that AJAX will be able to replace the fieldset.
'#prefix' => '<div id="names-fieldset-wrapper">',
'#suffix' => '</div>',
);
if (empty($form_state['num_names'])) {
$form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['names_fieldset']['name'][$i] = array(
'#type' => 'textfield',
'#title' => t('Name'),
);
}
$form['names_fieldset']['add_name'] = array(
'#type' => 'submit',
'#value' => t('Add one more'),
'#submit' => array('spower_add_more_add_one'),
// See the examples in ajax_example.module for more details on the
// properties of #ajax.
'#ajax' => array(
'callback' => 'spower_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
$form['names_fieldset']['remove_name'] = array(
'#type' => 'submit',
'#value' => t('Remove one'),
'#submit' => array('spower_add_more_remove_one'),
'#ajax' => array(
'callback' => 'spower_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
}
function spower_theme($existing, $type, $theme, $path) {
$base = array(
'render element' => 'form',
);
return array(
'spower_my_form' => $base + array(
'template' => 'spower',
),
);
}
function spower_add_more_callback($form, $form_state) {
return $form['names_fieldset'];
}
/**
* Submit handler for the "add-one-more" button.
*
* Increments the max counter and causes a rebuild.
*/
function spower_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
}
/**
* Submit handler for the "remove one" button.
*
* Decrements the max counter and causes a form rebuild.
*/
function spower_add_more_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 1) {
$form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}
The problem is that when I click "add more", the entire form is submitted.
If the above isn't clear, I've added the module at http://pastebin.com/Hn7bkM2v and the spower_elements.inc at http://pastebin.com/CwHW5mSm.
Thanks for the help.