13

I am dynamically populating <select> throught javascript in Drupal 7. The system gives me an error on submit:

"Illegal Choice has been detected"

How to mark, that this <select> must skip this error?

28

To solve the problem set '#validated' => 'TRUE' in your form element definition.

Example:
 form['my_dynamic_select'] = array(
 … 
 '#type' => 'select',
 '#validated' => TRUE
 …
 )

Reason:

If we are using a dynamically populated SELECT (dropdown) via AJAX this error will pop up. When a value is not present in options array, Drupal will consider it as illegal. So the user couldn't inject an illegal value into the database.

But in our case it's totally ok, so we need to use the attribute 'validated' => TRUE to skip the validation.

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

| improve this answer | |
  • This did not work for me though, diving deep into code, it says if !isset(#validated) then run the validations, but didnt work for my case though ... – Vaibhav Jain Feb 26 '15 at 3:42
  • 1
    This works for me in conjunction with $form['dynamic_field']['#webform_validated'] = TRUE – Teknotica Sep 15 '17 at 10:14
  • @Teknotica Thank you, you can edit the answer if you wish. – user4035 Sep 15 '17 at 11:56
  • Thank you so much!!!! Same issue, fixed now after putting '#validated' => TRUE – Manikandan Jul 24 '19 at 12:59
2

You need to do it on the server side, using a hook_form_alter() function and the #limit_validation_errors property of the Form API. You'll need to tweak it to suit your own needs but the following should help:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    $form['submit']['#limit_validation_errors'] = array();
  }
}

Be wary that the above will ignore all validation errors on the form. You'll need to put the names of the form elements that you do want to be validated in the #limit_validation_errors array.

| improve this answer | |
  • 2
    Keep in mind that "The #limit_validation_errors property is ignored if submit handlers will run, but the element doesn't have a #submit property, because it's too large a security risk to have any invalid user input when executing form-level submit handlers." Source: L1399 api.drupal.org/api/drupal/includes%21form.inc/function/… – Elijah Lynn Oct 14 '14 at 18:39

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