You are here

public static function SynonymsEntityAutocomplete::validateEntityAutocomplete in Synonyms 8

Form element validation handler for synonyms_entity_autocomplete elements.

File

src/Element/SynonymsEntityAutocomplete.php, line 111

Class

SynonymsEntityAutocomplete
Form element for synonyms-friendly entity autocomplete.

Namespace

Drupal\synonyms\Element

Code

public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
  $tokens = Tags::explode($form_state
    ->getValue($element['#parents']));
  $value = [];
  $autocomplete_service = \Drupal::getContainer()
    ->get('synonyms.behavior.autocomplete');
  foreach ($tokens as $token) {
    $entity_id = self::extractEntityIdFromAutocompleteInput($token);
    if (!$entity_id) {
      $lookup = $autocomplete_service
        ->autocompleteLookup($token, $element['#autocomplete_route_parameters']['token']);
      $lookup = array_shift($lookup);
      if ($lookup) {
        $entity_id = $lookup['entity_id'];
      }
    }
    if ($entity_id) {
      $value[] = [
        'target_id' => $entity_id,
      ];
    }
  }
  $form_state
    ->setValueForElement($element, $value);
}