I've created a form using Form API and AJAX for an add more button, but I think I have problems assigning names to the new ajax fields in the loops, cause when I try to insert my data into my database I get an error:
Undefined index
What am I doing wrong? Here's a section of my code:
<?php
function main_form_form($form, &$form_state) {
$form['group_tabs'] = array(
'#type' => 'horizontal_tabs',
'#attached' => array('library' => array(array('field_group', 'horizontal-tabs'))), // Converts fieldsets into tabs
);
$form['main_film_tab'] = array(
'#type' => 'fieldset',
'#title' => t('Film General Info'),
'#description' => t('Use this tab to enter basic info about the film.'),
'#group' => 'group_tabs',
);
$form_state['storage']['main_film_tab']['add_title'] = isset($form_state['storage']['main_film_tab']['add_title']) ? $form_state['storage']['main_film_tab']['add_title'] : 0;
$form['main_film_tab']['film_title']= array(
'#type' => 'textfield',
'#title' => t('Film Title'),
'#size' => 60,
'#maxlength' => 120,
'#required' => TRUE,
'#group' => 'main_film_tab',
'#description' => t('Enter Film Title.'),
'#attributes' => array(
'title' => t("Title of Film"),
)
);
$form['main_film_tab']['add_title'] = array(
'#type' => 'container',
'#tree' => TRUE,
'#prefix' => '<div id="add_title">',
'#suffix' => '</div>',
);
if ($form_state['storage']['main_film_tab']['add_title']) {
for ($i = 1; $i <= $form_state['storage']['main_film_tab']['add_title']; $i++) {
if ($i <= 2) {
$form['main_film_tab']['add_title'][$i] = array(
'#type' => 'fieldset',
'#tree' => TRUE,
);
$form['main_film_tab']['add_title'][$i]['main_film_tab']['film_title_'.$i] = array(
'#type' => 'textfield',
'#title' => t('Film Title '.$i),
'#size' => 60,
'#maxlength' => 120,
'#required' => FALSE,
'#group' => 'main_film_tab',
'#description' => t('Enter Film Title.'),
'#attributes' => array(
'title' => t("Title of Film"),
)
);
}
else {
return FALSE;
}
}
}
$form['main_film_tab']['button_add_title'] = array(
'#type' => 'button',
'#value' => t('Add another title.'),
'#href' => '',
'#ajax' => array(
'callback' => 'custom_registration_ajax_button_add_title',
'wrapper' => 'add_title',
),
);
$form['main_film_tab']['button_add_title']['#executes_submit_callback'] = FALSE;
$form['main_film_tab']['button_add_title']['#limit_validation_errors'] = array();
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Film Info'),
);
$form_state['storage']['main_film_tab']['add_title']++;
return $form;
}
function custom_registration_ajax_button_add_title($form, $form_state) {
return $form['main_film_tab']['add_title'];
}
function main_form_form_submit($form, &$form_state) {
$film_id = db_insert('film_main')
->fields(array(
'film_title' => $form_state['values']['film_title'],
'film_title_1' => $form_state['values']['film_title_1'],
'film_title_2' => $form_state['values']['film_title_2'],
))
->execute();
}