You are here

protected static function EntityAutocomplete::matchEntityByTitle in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php \Drupal\Core\Entity\Element\EntityAutocomplete::matchEntityByTitle()

Finds an entity from an autocomplete input without an explicit ID.

The method will return an entity ID if one single entity unambiguously matches the incoming input, and assign form errors otherwise.

Parameters

\Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler: Entity reference selection plugin.

string $input: Single string from autocomplete element.

array $element: The form element to set a form error.

\Drupal\Core\Form\FormStateInterface $form_state: The current form state.

bool $strict: Whether to trigger a form error if an element from $input (eg. an entity) is not found.

Return value

int|null Value of a matching entity ID, or NULL if none.

1 call to EntityAutocomplete::matchEntityByTitle()
EntityAutocomplete::validateEntityAutocomplete in core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php
Form element validation handler for entity_autocomplete elements.

File

core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php, line 318

Class

EntityAutocomplete
Provides an entity autocomplete form element.

Namespace

Drupal\Core\Entity\Element

Code

protected static function matchEntityByTitle(SelectionInterface $handler, $input, array &$element, FormStateInterface $form_state, $strict) {
  $entities_by_bundle = $handler
    ->getReferenceableEntities($input, '=', 6);
  $entities = array_reduce($entities_by_bundle, function ($flattened, $bundle_entities) {
    return $flattened + $bundle_entities;
  }, []);
  $params = [
    '%value' => $input,
    '@value' => $input,
  ];
  if (empty($entities)) {
    if ($strict) {

      // Error if there are no entities available for a required field.
      $form_state
        ->setError($element, t('There are no entities matching "%value".', $params));
    }
  }
  elseif (count($entities) > 5) {
    $params['@id'] = key($entities);

    // Error if there are more than 5 matching entities.
    $form_state
      ->setError($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)".', $params));
  }
  elseif (count($entities) > 1) {

    // More helpful error if there are only a few matching entities.
    $multiples = [];
    foreach ($entities as $id => $name) {
      $multiples[] = $name . ' (' . $id . ')';
    }
    $params['@id'] = $id;
    $form_state
      ->setError($element, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', [
      '%multiple' => strip_tags(implode('", "', $multiples)),
    ] + $params));
  }
  else {

    // Take the one and only matching entity.
    return key($entities);
  }
}