Drupal 7 - "illegal choice" error for ajaxed select field (not using Drupal FAPI #ajax)

2.1k views Asked by At

Trying to figure out how to solve an "illegal choice has been detected" error when using non FAPI ajax methods to replace a select list.

Example on node create form, there's a link below a select list to open a custom form in a ctools modal window to add a new value, and on successful submit of the form in the modal the node form select gets replaced with new values.

  <?php
  if (!empty($form_state['executed'])) {
    // Replace node form select if form submit was successful.
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('photo');
    $new_field = drupal_render($node_form[$field]);
    $output = array();
    $output[] = ajax_command_replace($selector, $new_field);
    $output[] = ctools_modal_command_dismiss();
  }
  print ajax_render($output);

I can get it to work until I submit the original node form, where I get an "illegal choice" error, presumably because the node form is using cached form values to validate. Setting $form_state['rebuild'] = TRUE; fixes the illegal choice error, but then an image field in the node form doesn't work properly. The image file gets uploaded and saved to node, but the thumbnail, alt and title tags don't get ajaxed in). Dblog gets this error because it tries posting data to the old form id (pre-rebuild).

location: file/ajax/field_image/und/0/form-DSbMdFlKNDaAJSFY4fVIHkcg2eMCDqYZHUfitCnR0VA
message: Invalid form POST data.

Is there a better way to replace the select list to avoid the "illegal choice" error, or should I be checking if there's a file module bug with $form_state['rebuild']? I couldn't find any documentation of how to trigger a $form #ajax event from another form, as a possible alternative. Not sure if that is possible at all. Any guidance would be appreciated.

1

There are 1 answers

0
tvanc On

On the node form select field, add '#validated' => TRUE. You'll have to alter the node form in a custom module:

mymodule_form_photo_node_form_alter (& $form, & $state)
{
  // Replace 'field_name' with whatever the name of the select field is
  $form['field_name']['#validated'] = TRUE;
}

I see this question was asked over a year ago, but hopefully this helps someone else looking for the answer.