I am updating a select list via Ajax - the list is an entity reference field with cardinality of 4. There is a plethora of "An illegal choice has been detected" results; however, none of them work for me. Typically they call for setting #validated = TRUE but it's also been noted several places that this solution does not work on multi select fields.

The parts to the ajax callback are:

// Only relevant because is a user that is added to entity reference list
$instructor_user = cela_events_cela_instructor_piggyback($form_state['values']['add_instructor_text']);
// Get a copy of an entity to pull allowed values from it
$entity = entity_create('event', array('type' => 'event'));
$values = $form_state['values']['field_instructors'][LANGUAGE_NONE];
if ($values == '_none') { $values = []; }
$event_form =  drupal_get_form("eck__entity__form_add_event_event", $entity);
$field = $event_form['field_instructors'];
// Update the field values to include the newly created instructor
$field[LANGUAGE_NONE]['#value'] = $values + [$instructor_user->uid => $instructor_user->uid];
$commands[] = ajax_command_replace('[id="instructors-wrapper"]', drupal_render($field));
$element = [
  '#type' => 'ajax',
  '#commands' => $commands,

return $element;

Note that I have confirmed, multiple times, that $field[LANGUAGE_NONE]['#options'] does contain the $instructor_user as an option.

What happens: A user Adds a new instructor via another field and the field in question, field_instructors is updated with the new instructor as an option, which is also a selected value as well. When I submit the form, I get the illegal choice error.

I have tried using $form_state['rebuild'] = true as well as updating $form_state['complete form'] (grasping at straws on that one). No matter what I've tried, _form_validate doesn't end up with the new user as an option.

Any ideas what I've done wrong?

  • Illegal choice as been detected can happen when the value of '#default_value' when your form renders is not one of the options available in '#options' ... Check the logic of how you determine the default value in your form callback. Are you setting the new value anywhere in the form_state in your ajax callback? In your form callback, you might have to check the form_state['input'] or $form_state['storage'] there before you default to the saved value... – jackrabbithanna Aug 16 '18 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.