NameAutocompleteController.php in Name Field 8
File
src/Controller/NameAutocompleteController.php
View source
<?php
namespace Drupal\name\Controller;
use Drupal\Core\Entity\EntityFieldManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\name\NameAutocomplete;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class NameAutocompleteController implements ContainerInjectionInterface {
protected $nameAutocomplete;
protected $entityFieldManager;
protected $entityTypeManager;
public function __construct(NameAutocomplete $name_autocomplete, EntityFieldManager $entityFieldManager, EntityTypeManagerInterface $entityTypeManager) {
$this->nameAutocomplete = $name_autocomplete;
$this->entityFieldManager = $entityFieldManager;
$this->entityTypeManager = $entityTypeManager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('name.autocomplete'), $container
->get('entity_field.manager'), $container
->get('entity_type.manager'));
}
public function autocomplete(Request $request, $field_name, $entity_type, $bundle, $component) {
$definitions = $this->entityFieldManager
->getFieldDefinitions($entity_type, $bundle);
if (!isset($definitions[$field_name])) {
throw new AccessDeniedHttpException();
}
$field_definition = $definitions[$field_name];
$access_control_handler = $this->entityTypeManager
->getAccessControlHandler($entity_type);
if ($field_definition
->getType() != 'name' || !$access_control_handler
->fieldAccess('edit', $field_definition)) {
throw new AccessDeniedHttpException();
}
$matches = $this->nameAutocomplete
->getMatches($field_definition, $component, $request->query
->get('q'));
return new JsonResponse($matches);
}
}