I've tried to build a form with #ajax submit function and rebuild the form. The following is my code.
function campaign_new_form($form, &$form_state){
if(!isset($form_state['num_names'])){
$form_state['num_names']=2;
}
// Create wrapper for ajax
$form['#prefix'] = '<div id="form-wrapper">';
$form['#suffix'] = '</div>';
for ($i = 1; $i <= $form_state['num_names']; $i++) {
$form['name_' . $i] = array(
'#type' => 'textfield',
'#title' => 'Value ' . $i,
'#required' => true
);
}
$form['add_button']= array(
'#type' => 'submit',
'#value'=> 'Add more',
'#ajax' => array(
'callback' => 'campaign_new_form_callback',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'form-wrapper',
),
);
return $form;
}
function campaign_new_form_callback($form, &$form_state){
$form_state['num_names']++;
$form_state['rebuild'] = true;
return $form;
}
It always renders two fields. What is the problem in my code?
$form_state['num_names']++
increases$form_state['num_names']
even when$form_state['num_names']
has not been defined?