entitytype_filter-1.0.x-dev/src/Controller/EntitiesAutoCompleteController.php

src/Controller/EntitiesAutoCompleteController.php
<?php

namespace Drupal\entitytype_filter\Controller;

use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a controller that watches autocomplete form elements.
 */
class EntitiesAutoCompleteController extends ControllerBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs an EntitiesAutoCompleteController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  /**
   * Generic autocomplete handler for all config entity types.
   */
  public function handle(string $config_entity_type, Request $request): JsonResponse {
    $results = [];
    $input = Xss::filter($request->query->get('q'));
    if (!$input) {
      return new JsonResponse($results);
    }

    if (!$this->entityTypeManager->hasDefinition($config_entity_type)) {
      return new JsonResponse($results);
    }

    $storage = $this->entityTypeManager->getStorage($config_entity_type);
    $definition = $this->entityTypeManager->getDefinition($config_entity_type);
    $label_key = $definition->getKey('label') ?? 'label';

    $query = $storage->getQuery()
      ->condition($label_key, $input, 'CONTAINS')
      ->range(0, 10);

    if ($definition->getKey('created')) {
      $query->sort($definition->getKey('created'), 'DESC');
    }

    $ids = array_keys($query->accessCheck(FALSE)->execute());
    $entities = $ids ? $storage->loadMultiple($ids) : [];

    foreach ($entities as $entity) {
      $results[] = [
        'value' => EntityAutocomplete::getEntityLabels([$entity]),
        'label' => $entity->label() . ' <small>(' . $entity->id() . ')</small>',
      ];
    }

    return new JsonResponse($results);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc