Drupal - "Illegal Choice has been detected"

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.


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.

Tags:

Forms