SearchController.php in Gutenberg 8.2
File
src/Controller/SearchController.php
View source
<?php
namespace Drupal\gutenberg\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\node\Entity\Node;
class SearchController extends ControllerBase {
public function search(Request $request) {
$search = (string) $request->query
->get('search');
$limit = (int) $request->query
->get('per_page', 20);
$query = \Drupal::entityQuery('node');
$query
->condition('title', $search, 'CONTAINS')
->condition('status', 1)
->sort('created', 'DESC')
->range(0, $limit);
$node_ids = $query
->execute();
$nodes = Node::loadMultiple($node_ids);
$result = [];
foreach ($nodes as $node) {
$result[] = [
'id' => $node
->id(),
'title' => $node
->getTitle(),
'type' => $node
->getType(),
'url' => $node
->toUrl('canonical', [
'absolute' => FALSE,
])
->toString(),
];
}
return new JsonResponse($result);
}
}