Hi List
I am trying to learn ajax stuff in Drupal 7.
I want to have a simple questionnaire form. Where I will have a single textfield.
In that text field one will type a question category, and if he wants to type more question categories, user need to click a button "Add More Categories".
The whole source code is at the end of this email. When ajax callback fires, I want to remember how many textfields I need to add, so that when a section of form is updated in _form() hook, I can according add those many textfields.
I am trying to manage that using a variable "$all_categories" and form element $form['all_categories'] (of type value).
I tried many options, always I find $all_categories value is 1. So I am unable to add more textfields.
My observation is whatever I set in ajax callback, in _form hook api, I find value is lost.
Kindly guide me what I am missing.
Best Regards
Kamal
NECS, Bangalore
<?php
function questionnaire_menu() {
$items = array();
$items['questionnaire/form/manage'] = array(
'title' => t('Manage questions'),
'page callback' => 'questionnaire_form',
'access arguments' => array('question manage'),
'type' => MENU_SUGGESTED_ITEM,
);
return $items;
}
function questionnaire_permission()
{
return array(
'question manage' => array(
'title' => t('Question management'),
'description' => t('Provides question management capability'),
),
);
}
function questionnaire_form()
{
return drupal_get_form('questionnaire_my_form');
}
function questionnaire_my_form($form, &$form_state)
{
$form_state['cache'] = TRUE;
$all_categories = !empty($form_state['values']['all_categories']) ? $form_state['values']['all_categories'] : 1;
$form['all_categories'] = array(
'#type' => 'value',
'#default_value' => $all_categories,
'#value' => $all_categories);
// The prefix/suffix provide the div that we're replacing, named by
// #ajax['wrapper'] above.
$form['category_fieldset'] = array(
'#title' => t("Questions Categories"),
'#prefix' => '<div id="category-div">',
'#suffix' => '</div>',
'#type' => 'fieldset',
'#description' => t('Please enter the question categories'),
);
for ($i=1; $i<= $all_categories ; $i++)
{
$key = 'ctg' . $i;
$form['category_fieldset']['category'][$key] = array(
'#type' => 'textfield',
'#title' => "Question category $i",
);
}
$form['category_fieldset']['add_more_category'] = array(
'#type' => 'submit',
'#value' => t('Add More Categories'),
'#ajax' => array(
'callback' => 'questionnaire_category_callback',
'wrapper' => 'category-div',
'method' => 'replace',
'effect' => 'fade',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function questionnaire_category_callback($form, &$form_state)
{
$form_state['values']['all_categories'] = $form_state['values']['all_categories'] + 1;
return $form['category_fieldset'];
}
?>