AutocompleteController.php in Quick Node Block 8
File
src/Controller/AutocompleteController.php
View source
<?php
namespace Drupal\quick_node_block\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AutocompleteController extends ControllerBase {
protected $connection;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('database'));
}
public function autocomplete(Request $request) {
$typed = $request->query
->get('q');
$matches = [];
$query = $this->connection
->select('node_field_data', 'n');
$query
->addField('n', 'nid');
$query
->addField('n', 'title');
$db_or = $query
->orConditionGroup();
$db_or
->condition('n.title', '%' . $typed . '%', 'LIKE');
$db_or
->condition('n.nid', $typed, '=');
$query
->condition($db_or);
$results = $query
->execute()
->fetchAllKeyed(0, 1);
foreach ($results as $nid => $title) {
$matches[] = [
'value' => $title . ' (' . $nid . ')',
'label' => $title,
];
}
return new JsonResponse($matches);
}
}