public function AutocompleteWidget::elementValidate

Overrides \Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()

Overrides AutocompleteWidgetBase::elementValidate

File

drupal/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php, line 59
Contains \Drupal\entity_reference\Plugin\field\widget\AutocompleteWidget.

Class

AutocompleteWidget
Plugin implementation of the 'entity_reference autocomplete' widget.

Namespace

Drupal\entity_reference\Plugin\field\widget

Code

public function elementValidate($element, &$form_state, $form) {
  $auto_create = isset($this->instance['settings']['handler_settings']['auto_create']) ? $this->instance['settings']['handler_settings']['auto_create'] : FALSE;

  // If a value was entered into the autocomplete.
  $value = '';
  if (!empty($element['#value'])) {

    // Take "label (entity id)', match the id from parenthesis.
    if (preg_match("/.+\\((\\d+)\\)/", $element['#value'], $matches)) {
      $value = $matches[1];
    }
    else {

      // Try to get a match from the input string when the user didn't use the
      // autocomplete but filled in a value manually.
      $handler = entity_reference_get_selection_handler($this->field, $this->instance);
      $value = $handler
        ->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create);
    }
    if (!$value && $auto_create && count($this->instance['settings']['handler_settings']['target_bundles']) == 1) {

      // Auto-create item. see entity_reference_field_presave().
      $value = array(
        'target_id' => 0,
        'entity' => $this
          ->createNewEntity($element['#value'], $element['#autocreate_uid']),
        // Keep the weight property.
        '_weight' => $element['#weight'],
      );

      // Change the element['#parents'], so in form_set_value() we
      // populate the correct key.
      array_pop($element['#parents']);
    }
  }
  form_set_value($element, $value, $form_state);
}