1

I have a form in Drupal. On a select list I am using the ajax built into the form api to trigger a callback on change.

I need to be able to add an option to the select list via javascript. Set the value on the select list to be that new value and then trigger the ajax call.

I have something like:

var select_list = $('#edit-example');

select_list.append($("<option></option>")
  .attr("value", data.ObjectID)
  .text(data.Name));
select_list.val(data.ObjectID);
select_list.change();

Where data is a JSON object.

So the option is being added to the select list. The value has changed to my new option. I trigger the ajax event. However I am getting the error message:

An illegal choice has been detected. Please contact the site administrator.

The callback is working fine except the error is displayed. What can I do to stop this message appearing?

marked as duplicate by Mołot, Letharion, AjitS, Bala, Jimajamma Jan 28 '14 at 4:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

Upon validation, the FAPI checks that the values given for any select/option/radios match what was originally available when the form was first built. This is a security check, and is built in to all form processing.

Changing the values of an existing select list with javascript means your form has been altered outside of Drupal's control (perhaps maliciously, the FAPI cannot know), and so the validation fails.

To stop the message appearing, you should use the AJAX framework to build you form, instead of manipulating it directly with jQuery.

Not the answer you're looking for? Browse other questions tagged or ask your own question.