Drupal 7 Forms API - AJAX Forms error: An illegal choice has been detected. Please contact the site administrator - drupal-7

I have a form set up where a users selects an item from a drop down. Once that item is selected another drop down is populated. Then depending on the value that is selected from the second drop down a fieldset may or may not be shown. If the field set is shown there is a field and a button. By clicking the button you add another copy of the same field. Once there is more than one a remove one button shows up as well. I got the basis for the code from here:
http://api.drupal.org/api/examples/ajax_example%21ajax_example_graceful_degradation.inc/function/ajax_example_add_more/7
The problem is when I click 'Add Another Survey Question' the first time it works fine and add a field. When I click it a second time or when I click remove now that there are two, I get this error: 'An illegal choice has been detected. Please contact the site administrator.'
What am I doing wrong?
Here's my code:
function touchpoints_addmetric_form($form, &$form_state, $tp_id) {
$selectedType = isset($form_state['values']['type']) ? $form_state['values']['type'] : FALSE;
$types = db_query('SELECT * FROM {touchpoints_metric_types}') -> fetchAllKeyed(0, 1);
$form['#tree'] = TRUE;
$form['type'] = array(
'#type' => 'select',
'#title' => t('Metric Type'),
'#options' => $types,
'#required'=>TRUE,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'method-wrapper',
'callback' => 'touchpoints_method_callback'
)
);
$form['measurementmethod'] = array(
'#type' => 'select',
'#title' => t('Measurement Method'),
'#required'=>TRUE,
'#prefix' => '<div id="method-wrapper">',
'#suffix' => '</div>',
'#options' => _get_methods($selectedType)
);
$form['survey'] = array('
#type' => 'fieldset',
'#collapsible' => FALSE,
'#states' => array(
'visible' => array(
array(
array(':input[name="measurementmethod"]' => array('value' => '5')),
'xor',
array(':input[name="measurementmethod"]' => array('value' => '6')),
'xor',
array(':input[name="measurementmethod"]' => array('value' => '7'))
)
)
)
);
$form['survey']['contents'] = array(
'#type' => 'fieldset',
'#collapsible' => FALSE,
'#prefix' => '<div id="survey-div">',
'#suffix' => '</div>',
);
if (empty($form_state['num_surveys'])) {
$form_state['num_surveys'] = 1;
}
for ($i = 1; $i <= $form_state['num_surveys']; $i++) {
$form['survey']['contents']['survey_question'][$i] = array(
'#type' => 'textfield',
'#title' => t('Survey Question ' . $i),
'#size' => 70, '#maxlength' => 100,
);
}
$form['survey']['contents']['addsurvey'] = array(
'#type' => 'submit',
'#value' => t('Add Another Survey Question'),
'#submit' => array('touchpoints_metrics_survey_add_one'),
'#limit_validation_errors' => array(),
'#ajax' => array(
'callback' => 'touchpoints_metrics_survey_callback',
'wrapper' => 'survey-div',
),
);
if ($form_state['num_surveys'] > 1) {
$form['survey']['contents']['removesurvey'] = array(
'#type' => 'submit',
'#value' => t('Remove A Survey Question'),
'#submit' => array('touchpoints_metrics_survey_remove_one'),
'#limit_validation_errors' => array(),
'#ajax' => array(
'callback' => 'touchpoints_metrics_survey_callback',
'wrapper' => 'survey-div',
),
);
}
return $form;
}
function _get_methods($selected) {
if ($selected) {
$methods = db_query("SELECT * FROM {touchpoints_m_methods} WHERE mt_id=$selected") -> fetchAllKeyed(0, 2);
} else {
$methods = array();
}
return $methods;
}
function touchpoints_method_callback($form, &$form_state) {
return $form['measurementmethod'];
}
function touchpoints_metrics_survey_add_one($form, &$form_state) {
$form_state['num_surveys']++;
$form_state['rebuild'] = TRUE;
}
function touchpoints_metrics_survey_remove_one($form, &$form_state) {
if ($form_state['num_surveys'] > 1) {
$form_state['num_surveys']--;
}
$form_state['rebuild'] = TRUE;
}
function touchpoints_metrics_survey_callback($form, &$form_state) {
return $form['survey']['contents'];
}

I have encountered this error a few times, and this is what I found:
This is Drupal's way of saying "Hey, you tried to submit this form with a , checkbox or radio button option that wasn't included in the original form definition! That's not allowed." - See more at: http://proofgroup.com/blog/2008/jul/debugging_mysterious_illegal_choice_has_been_detected_please_contact_site_administrato#sthash.vDNmqslL.dpuf
Instead of custom code, maybe you should consider module Conditional Fields
Or a work around: '#validate' => TRUE source

Actually, it's '#validated' => TRUE.

Related

How to create an image button that behaves like a button in drupal 7?

How I want it to work:
I have list of buttons(type button) that trigger an Ajax call that add the that item to a list. This works as exactly as I want it except for the button looks ugly .
The problem:
When I try to replace the "button" with an "image button" the form is submitted, which is not what I want. Is there a way to add an image to a button that do not trigger a submit? Can I disable the submit for "image button"? Or shall I add the image using css on the button?
What is the difference between "button", "image button" and "submit"?
To make the type image_button act like an button is looked in system.module and found "'#executes_submit_callback' => TRUE", so change this to false will prevent submit function to be called on your image_button.
Code from system.module:
$types['button'] = array(
'#input' => TRUE,
'#name' => 'op',
'#button_type' => 'submit',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => FALSE,
'#process' => array('ajax_process_form'),
'#theme_wrappers' => array('button'),
);
$types['image_button'] = array(
'#input' => TRUE,
'#button_type' => 'submit',
'#executes_submit_callback' => TRUE, // <--- This is why submit is triggered
'#limit_validation_errors' => FALSE,
'#process' => array('ajax_process_form'),
'#return_value' => TRUE,
'#has_garbage_value' => TRUE,
'#src' => NULL,
'#theme_wrappers' => array('image_button'),
);
Another thing that you might encounter is the validation error, to remove it just add the "'#validate' => array()" or if you want to run validation but ignore errors use "#limit_validation_errors' => array()". This also apply for button.
Here is an example where you can experiment the above things and see when the validation and submit callback is triggered. Also a checkbox is included to show when validation errors occurs.
function button_menu()
{
$items = array();
$items['button'] = array(
'title' => 'Button',
'page callback' => 'drupal_get_form',
'page arguments' => array('button_form'),
'access callback' => array(TRUE),
'type' => MENU_CALLBACK,
);
return $items;
}
function button_form($form, &$form_state)
{
// Add to prove the point of how validation is working
$form['checkbox'] = array(
'#type' => 'checkbox',
'#title' => t('checkbox'),
'#default_value' => FALSE,
);
$form['button'] = array(
'#id' => 'button_1',
'#type' => 'button',
'#name' => 'test1',
'#value' => 'test1',
//'#validate' => array(), // This line will remove validation completely
'#limit_validation_errors' => array(), // This line will run validation but ignore any errors
'#ajax' => array(
'callback' => 'button_test_callback',
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
);
$form['image_button'] = array(
'#id' => 'image_button_1',
'#type' => 'image_button',
'#src' => '/themes/bartik/logo.png', // hope you still have bartik theme
'#executes_submit_callback' => FALSE, // This line removes the submit callback
//'#validate' => array(), // This line will remove validation completely
'#limit_validation_errors' => array(), // This line will run validation but ignore any errors
'#ajax' => array(
'callback' => 'button_test_callback',
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
);
// Just some code to show what button was pressed
if (array_key_exists('triggering_element', $form_state) &&
($form_state['triggering_element']['#id'] == 'button_1' || $form_state['triggering_element']['#id'] == 'image_button_1'))
{
$form['markup'] = array(
'#type' => 'markup',
'#markup' => '<div id="wrapper"><p>'. $form_state['triggering_element']['#id'] .'</p></div>',
);
}
else {
$form['markup'] = array(
'#type' => 'markup',
'#markup' => '<div id="wrapper"><p>nothing</p></div>',
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function button_test_callback($form, $form_state)
{
return $form['markup'];
}
function button_form_validate($form, &$form_state)
{
// To display when validation is triggered
drupal_set_message('button_form_validate');
// Only when submit button is pressed we care about this error.
if ( $form_state['values']['checkbox'] == 0) {
form_set_error('checkbox', 'checkbox not checked');
}
}
function button_form_submit($form, &$form_state)
{
// To display when submit is triggered
drupal_set_message('button_form_submit');
}

drupal 7 ajax framework example does not work

I want to add one form in user profile page. So i created user-profiled.tpl.php. In that template,i just copied the example from ajax framework for testing. Here is the whole codes:
function ajax_example_simplest($form, &$form_state) {
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'ajax_example_simplest_callback',
'wrapper' => 'replace_textfield_div',
),
);
$form['replace_textfield'] = array(
'#type' => 'textfield',
'#title' => t("The default value will be changed"),
'#description' => t("Say something about why you chose") . "'" .
(!empty($form_state['values']['changethis'])
? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_example_simplest_callback($form, $form_state) {
return $form['replace_textfield'];
}
I am confusing now. After i clicked the checkbox, nothing change in textfield. My jquery version is 1.9. Is there any other constraints?
The change is in description and not in textfield(I did the same error first as you did). However I have updated the code so it also shows the value in 'textfield'.
function ajax_example_simplest($form, &$form_state)
{
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'ajax_example_simplest_callback2',
'wrapper' => 'replace_textfield_div',
),
);
$number = (!empty($form_state['values']['changethis']) ? $form_state['values']['changethis'] : t("Not changed yet"));
$form['replace_textfield'] = array(
'#type' => 'textfield',
'#title' => t("The default value will be changed"),
// Not that value was changed in the description
'#description' => t("Say something about why you chose") . " '" . $number . "'",
// Also add next line if you want to see it in the text box
'#value' => $number,
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_example_simplest_callback2($form, $form_state) {
return $form['replace_textfield'];
}

Drupal Submit handler is not called properly in custom module

I have this code for calling a form and than submit it..
<?php
// hook_menu
function pricepackages_menu()
{
$items = array();
$items['membership/packages'] = array(
'title' => t('Manage Membership Packages'),
'page callback' => 'drupal_get_form',
'page arguments' => array('pricepackages_form'),
//'access callback' => TRUE,
'access arguments' => array('access administration pages'),
);
return $items;
}
// FORM SHOW HOOK
function pricepackages_form($form, &$form_state)
{
$form = array();
$form['packagename'] = array(
'#type' => 'textfield',
'#title' => 'Package Name',
//'attribute' => array('class' => 'package'),
'#required' => TRUE,
);
$form['packageDescp'] = array(
'#type' => 'textfield',
'#title' => 'Package Short Description',
//'attribute' => array('class' => 'package'),
'#required' => FALSE,
);
$form['price'] = array(
'#type' => 'textfield',
'#title' => 'Package Price',
//'attribute' => array('class' => 'package'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
$form['submit'][] = array('package_get_form'=> array());
return $form;
}
function package_get_form($form, &$form_state)
{
drupal_set_message('working');
?>
<script language="javascript">
alert("aaa");
</script>
<?php
return;
}
?>
but this one is not wokring proerly and form is not being submitted on the specific form...
neither its showing alert or message...
please help me...
This part is not correct:
$form['submit'][] = array('package_get_form'=> array());
To add a submit callback, simply write:
$form['submit'][] = 'package_get_form';
You don't even need this line since the form API provides a default callback appending "_submit" to the form id/callback. For your case:
pricepackages_form_submit()

form submission in Drupal

i have made a custom module for form in drupal using dupal API,and made a table in my database
What i want is to save the value of drop down box instead of it's index into database...my .module file is:
<?php
function form_test_menu() {
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
return $items;
}
function form_test_form($form,&$form_submit) {
$form['name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['college'] = array(
'#title' => t('College/University'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['education'] = array(
'#title' => t('Education'),
'#type' => 'select',
'#description' => 'Select your higher education .',
'#options' => array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate')),
'#required' => TRUE,
);
$form['percentage'] = array(
'#title' => t('Percentage/CGPA'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['application'] = array(
'#title' => t('Job Applied'),
'#type' => 'select',
'#options' => array(t('---select---'),t('Web Developer'),t('Web Designer'),t('SEO'),t('Marketing')),
'#required' => TRUE,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
function form_test_form_submit($form, $form_state) {
global $user;
// Here u can insert Your custom form values into your custom table.
db_insert('drupal')
->fields(array(
'name' => $form_state['values']['name'],
'college' => $form_state['values']['college'],
'education' => $form_state['values']['education'],
'percentage' => $form_state['values']['percentage'],
'application' => $form_state['values']['application'],
))->execute();
drupal_set_message("successfully saved data");
}
?>
All are in one file(.module)....any help will be appreciated.
Thank you.
The solution is to pass options array from one function to another. To achieve that use the second argument of "form_test_form" and "form_test_form_submit" functions.
function form_test_form($form,&$form_submit) {
$form_submit['myoptions'] = array(' select', 'option1' .....
}
Then
function form_test_form_submit($form,&$form_state) {
$myoptions = $form_state['myoptions']; etc ...
}

drupal 7 ajax form rebuild form to change form_state value

I have one drupal form, i want it works as "add one more": there is one button at the end of the form, when click it, another form will append to it. Here is part of my code:
function add_passenger_form($form, &$form_state){
if(!isset($form_state['num_names'])){
$form_state['num_names']=2;
}
$form['add_button']= array(
'#type' => 'button',
'#value'=> 'Add more',
'#ajax' => array(
'callback' => 'ajax_add_passenger_callback',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'last_field',
),
);
$form['form_number']=array(
'#prefix'=>'<div class="form_number">',
'#suffix'=>'</div>',
'#type'=>'hidden',
'#value'=>2,
);
}
function ajax_add_passenger_callback($form, &$form_state){
$form_state['num_names']++;
$form_state['rebuild']=TRUE;
$form['form_number']['#value']=$form_state['num_names'];
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace(".form_number", render($form['form_number'])),
)
);
}
I want the $form['num_names']['#value'] increase one when i click the add one button. Now it only works once (to 3).
Change your code like this.. this will create button "Add more" to add new passenger and one field (name) for each passenger. You can replace that "Name" field for example with fieldset and add more fields for one passenger.
function add_passenger_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 = 0; $i < $form_state['num_names']; $i++) {
$form['name_' . $i] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#required' => true
);
}
$form['add_button']= array(
'#type' => 'button',
'#value'=> 'Add more',
'#ajax' => array(
'callback' => 'ajax_add_passenger_callback',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'form-wrapper',
),
);
}
function ajax_add_passenger_callback($form, &$form_state){
$form_state['num_names']++;
// rebuild whole form with new values
$form_state['rebuild'] = true;
}
Also check this link for more info about ajax:
https://api.drupal.org/api/examples/ajax_example!ajax_example_graceful_degradation.inc/7
function add_passenger_form($form, &$form_state){
$form['#tree'] = TRUE;
if(empty($form_state['num_names'])){
$form_state['num_names'] = 2;
}
$form['passenger_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('List of Passengers'),
'#prefix' => '<div id="passenger-form-wrapper">',
'#suffix' => '</div>',
);
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['passenger_fieldset']['passenger_name'][$i] = array(
'#type' => 'textfield',
'#title' => t('Passenger Name'),
'#required' => false,
);
}
$form['passenger_fieldset']['add_button']= array(
'#type' => 'submit',
'#value'=> t('Add passenger'),
'#submit' => array('add_passenger_form_add_one'),
'#ajax' => array(
'callback' => 'add_passenger_form_callback',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'passenger-form-wrapper',
),
);
// Remove passenger
if ($form_state['num_names'] > 2) {
$form['passenger_fieldset']['remove_button'] = array(
'#type' => 'submit',
'#value' => t('Remove Passenger'),
'#submit' => array('remove_passenger_form_remove_one'),
'#ajax' => array(
'callback' => 'add_passenger_form_callback',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'passenger-form-wrapper',
),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/*
* add a textfield one more
*/
function add_passenger_form_add_one($form, &$form_state) {
$form_state['num_names']++;
// rebuild whole form with new values
$form_state['rebuild'] = true;
}
function remove_passenger_form_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 2) {
$form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}
function add_passenger_form_callback($form, $form_state){
return $form['passenger_fieldset'];
}

Resources