public function EntityReferenceController::handleAutocomplete

Autocomplete the label of an entity.

Parameters

Request $request: The request object that contains the typed tags.

string $type: The widget type (i.e. 'single' or 'tags').

string $field_name: The name of the entity reference field.

string $entity_type: The entity type.

string $bundle_name: The bundle name.

string $entity_id: (optional) The entity ID the entity reference field is attached to. Defaults to ''.

Return value

\Symfony\Component\HttpFoundation\JsonResponse The matched labels as json.

Throws

\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Throws access denied when either the field or field instance does not exists or the user does not have access to edit the field.

1 string reference to 'EntityReferenceController::handleAutocomplete'
entity_reference.routing.yml in drupal/core/modules/entity_reference/entity_reference.routing.yml
drupal/core/modules/entity_reference/entity_reference.routing.yml

File

drupal/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceController.php, line 71
Contains \Drupal\entity_reference/EntityReferenceController.

Class

EntityReferenceController
Defines route controller for entity reference.

Namespace

Drupal\entity_reference

Code

public function handleAutocomplete(Request $request, $type, $field_name, $entity_type, $bundle_name, $entity_id) {
  if (!($field = field_info_field($field_name))) {
    throw new AccessDeniedHttpException();
  }
  if (!($instance = field_info_instance($entity_type, $field_name, $bundle_name))) {
    throw new AccessDeniedHttpException();
  }
  if ($field['type'] != 'entity_reference' || !field_access('edit', $field, $entity_type)) {
    throw new AccessDeniedHttpException();
  }

  // Get the typed string, if exists from the URL.
  $items_typed = $request->query
    ->get('q');
  $items_typed = drupal_explode_tags($items_typed);
  $last_item = drupal_strtolower(array_pop($items_typed));
  $prefix = '';

  // The user entered a comma-separated list of entity labels, so we generate
  // a prefix.
  if ($type == 'tags' && !empty($last_item)) {
    $prefix = count($items_typed) ? drupal_implode_tags($items_typed) . ', ' : '';
  }
  $matches = $this->entityReferenceAutocomplete
    ->getMatches($field, $instance, $entity_type, $entity_id, $prefix, $last_item);
  return new JsonResponse($matches);
}