I am trying to add a combination of text field and a select box to a form dynamically using Drupal 7 Ajax, when i click on a button.
But i have 2 issues here:
- I am not able to add more than 1 set of fields in the form with Ajax
- After i submit the form, i am not able to retrieve the values of the form. They are empty. I have the fields as "name_1", "select_1", "name_2", "select_2", etc.
I want to know if there is any way to solve it, with / without using a fieldset.
My custom module code:
function my_form_form($form, &$form_state, $no_js_use = FALSE) {
$form['#tree'] = TRUE;
$form['add_more'] = array(
'#type' => 'button',
'#value' => t('Add More'),
'#href' => '',
'#ajax' => array(
'callback' => 'ajax_simplest_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
$form['names']['name_1'] = array(
'#type' => 'textfield',
'#title' => t('Name 1'),
'#attributes'=>array('id'=>'name_1', 'name'=>'name_1'),
);
$form['names']['select_1'] = array(
'#type' => 'select',
'#title' => t('Select 1'),
'#attributes'=>array('id'=>'select_1', 'name'=>'select_1'),
'#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
$form['#submit'][] = 'my_form_add_more_submit';
return $form;
}
function ajax_simplest_callback($form, &$form_state) {
if (empty($form_state['num_names'])) {
$form_state['num_names'] = 1;
}
else {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
}
for ($i = 1; $i < $form_state['num_names']; $i++) {
$form['names']['name_'.$i+1] = array(
'#type' => 'textfield',
'#title' => t('Name '.$i+1),
'#attributes'=>array('id'=>'name_'.$i+1, 'name'=>'name_'.$i+1),
);
$form['names']['select_'.$i+1] = array(
'#type' => 'select',
'#title' => t('Select '.$i+1),
'#attributes'=>array('id'=>'select_'.$i+1, 'name'=>'select_'.$i+1),
'#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
);
}
return $form['names'];
}
function my_form_add_more_submit($form, &$form_state) {
print_r($form_state['values']);
exit();
}
names-fieldset-wrapper
– Sumit Madan Apr 17 '13 at 16:15