1

I am trying to use latest select2.js (4.0.1) with drupal select2widget module. As per select2 documentation I have changed the "select2widget_field_widget_form" for "select2widgetajax" option from "hidden" to "select list" field as follows-

case 'entityreference':
      $options=array();
      foreach ($items as $key => $value) {
          dsm($value);
          $uid = $value['target_id'];
             $user = user_load($uid);
             $user_wrapper = entity_metadata_wrapper('user', $user);
             $options[$uid] = $user_wrapper->field_full_name->value();

         }

    // Check original field configuration
    if (!empty($instance['field_mode']) && !empty($form_state['field'][$field['field_name']][LANGUAGE_NONE]['instance']['widget']['type'])
      && $form_state['field'][$field['field_name']][LANGUAGE_NONE]['instance']['widget']['type'] == 'og_complex') {
      $autocomplete_path .= '?field_mode=' . $instance['field_mode'];
    }



    $default_value = _options_storage_to_form($items, $options, $value_key, $properties);

  $element += array(
    '#type' => 'select',

    '#default_value' => $default_value, 
    // Do not display a 'multiple' select box if there is only one option.
    '#multiple' => TRUE  ,
    '#options' =>  $options,
    '#process' => array('select2widget_entity_process_callback', 'ajax_process_form'),
    '#value_key' => $value_key,
    '#settings' => $instance['widget']['settings'],
    '#element_validate' =>  array('select2widget_field_widget_validate'),
    '#properties' => $properties,
     '#autocomplete_path' => $autocomplete_path, 
  );
  break;
}

Everything works fine. Select2 is populated perfectly and I can select from the list also. But when I want to save the form it is throughing the error like:

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

After doing some google I came to know that 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.

I've tried this solution as explained here and added:

$element['#validated'] = TRUE;

in my field_widget_form. But no luck.

1
  • If you are using any other Ajax function other than #autocomplete_path then try to recreate the whole element again in that function and return form. Commented Jun 13, 2016 at 9:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.