You are here

public function AutocompleteController::autocomplete in Quick Node Block 8

Retrieves suggestions for block category autocompletion.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing autocomplete suggestions.

1 string reference to 'AutocompleteController::autocomplete'
quick_node_block.routing.yml in ./quick_node_block.routing.yml
quick_node_block.routing.yml

File

src/Controller/AutocompleteController.php, line 52

Class

AutocompleteController
Defines a route controller for entity autocomplete form elements.

Namespace

Drupal\quick_node_block\Controller

Code

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);
}