You are here

protected static function EntityAutocomplete::matchEntityByTitle in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 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 unambuguously matches the incoming input, and sill assign form errors otherwise.

Parameters

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

integer|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 249
Contains \Drupal\Core\Entity\Element\EntityAutocomplete.

Class

EntityAutocomplete
Provides an entity autocomplete form element.

Namespace

Drupal\Core\Entity\Element

Code

protected static function matchEntityByTitle($handler, $input, &$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 = array(
    '%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 = array();
    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)".', array(
      '%multiple' => implode('", "', $multiples),
    )));
  }
  else {

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