15

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?

0

2 Answers 2

30

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.

4
  • 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 ... Commented Feb 26, 2015 at 3:42
  • 1
    This works for me in conjunction with $form['dynamic_field']['#webform_validated'] = TRUE
    – Teknotica
    Commented Sep 15, 2017 at 10:14
  • @Teknotica Thank you, you can edit the answer if you wish.
    – user4035
    Commented Sep 15, 2017 at 11:56
  • Thank you so much!!!! Same issue, fixed now after putting '#validated' => TRUE
    – Manikandan
    Commented Jul 24, 2019 at 12:59
3

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.

1
  • 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/… Commented Oct 14, 2014 at 18:39

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