0

I'm creating a search results page using the Search API. I want to set an url like this:

    /search/{text}

How should i set up my route? It must accept any combination of characters, including non-ascii, spaces, numbers, etc, but it must not be empty.

This is my current routing rule. As you can see, there is no restriction for the text parameter:

    my.search.results:
      path: '/search/{text}'
      defaults:
        text: NULL
        _controller: '\Drupal\my\Controller\SearchController::results'
        _title: 'Search Results'
      requirements:
        _permission: 'access content'
3
  • I think you might want to set text to \w+, but I am not 100% certain. See: symfony.com/doc/current/routing/requirements.html Plus, it should go under requirements.
    – Kevin
    Commented Jul 10, 2017 at 17:10
  • 2
    Symfony placeholders are required unless told otherwise - just remove the default value?
    – Clive
    Commented Jul 10, 2017 at 17:12
  • \w+ will fail if there is a space (%20) between words. Removing the default value will do the trick. Commented Jul 10, 2017 at 17:17

1 Answer 1

0

As long as a default value isn't provided in the route definition, every route placeholder is required. Defining the route as follow is sufficient.

my.search.results:
  path: '/search/{text}'
  defaults:
    _controller: '\Drupal\my\Controller\SearchController::results'
    _title: 'Search Results'
  requirements:
    _permission: 'access content

See, for example, the definition of the dblog.event route in the dblog.routing.yml file.

dblog.event:
  path: '/admin/reports/dblog/event/{event_id}'
  defaults:
    _controller: '\Drupal\dblog\Controller\DbLogController::eventDetails'
    _title: 'Details'
  requirements:
    _permission: 'access site reports'

The controller associated to that route, DbLogController::eventDetails(), doesn't check the value of $event_id is an empty string, simply because it won't get an empty string for that parameter.

public function eventDetails($event_id) {
  $dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [
    ':id' => $event_id,
  ])
    ->fetchObject();
  if (empty($dblog)) {
    throw new NotFoundHttpException();
  }
  // …
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.