Skip to content
Snippets Groups Projects
Commit 474e3a6d authored by Robert Phillips's avatar Robert Phillips
Browse files

Issue #3323856 by robphillips: Autocomplete controller to lookup routes.

parent d2c9ec9c
Branches
Tags
No related merge requests found
dynamic_path_aliases.autocomplete:
path: "/path-rewrite/autocomplete"
defaults:
_controller: Drupal\dynamic_path_aliases\Controller\PathRewriteAutocompleteController::autocomplete
_format: json
requirements:
_permission: "administer dynamic path rewrites"
<?php
namespace Drupal\dynamic_path_aliases\Controller;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides path rewrite route autocomplete controller.
*/
class PathRewriteAutocompleteController extends ControllerBase {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected Connection $connection;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->connection = $container->get('database');
return $instance;
}
/**
* Autocomplete callback.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Returns JSON response of results.
*/
public function autocomplete(Request $request): JsonResponse {
if (!($input = Xss::filter($request->query->get('q')))) {
return new JsonResponse([]);
}
$query = $this->connection->select('router')
->fields('router', ['name', 'path'])
->range(0, 10);
$input = '%' . $query->escapeLike($input) . '%';
$query->condition($query->orConditionGroup()
->condition('name', $input, 'LIKE')
->condition('path', $input, 'LIKE'));
$query->orderBy('path');
$items = [];
foreach ($query->execute() as $result) {
$items[] = [
'value' => $result->name,
'label' => $result->path,
];
}
return new JsonResponse(array_values($items));
}
}
......@@ -78,6 +78,7 @@ class PathRewriteForm extends EntityForm {
'#type' => 'textfield',
'#title' => $this->t('Route name'),
'#description' => $this->t('Route to rewrite its path. Search by route name or path.'),
'#autocomplete_route_name' => 'dynamic_path_aliases.autocomplete',
'#required' => TRUE,
'#default_value' => $this->entity->get('route_name'),
];
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment