Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Modules and Hooks

Routes and Controllers

Add custom pages to Drupal: routing.yml, controllers returning render arrays, path parameters, access requirements, menu links and a runnable route-matching stand-in.

A route connects a URL path to some PHP code that produces a response. Drupal 8 and later use the Symfony routing component, so a custom page needs two things: a route defined in YAML and a controller method that returns content. Menu links, tabs and actions are separate YAML files that point to routes by name.

The PHP and YAML below are read-only. The TryIt blocks implement a tiny router in JavaScript so you can see how patterns, parameters and requirements work together.

Defining a route

In tutorial_notes.routing.yml:

YAML
tutorial_notes.overview:
  path: '/notes'
  defaults:
    _controller: '\Drupal\tutorial_notes\Controller\NotesController::overview'
    _title: 'Notes'
  requirements:
    _permission: 'access content'

tutorial_notes.view:
  path: '/notes/{note_id}'
  defaults:
    _controller: '\Drupal\tutorial_notes\Controller\NotesController::view'
    _title_callback: '\Drupal\tutorial_notes\Controller\NotesController::title'
  requirements:
    _permission: 'access content'
    note_id: '\d+'

The key (tutorial_notes.overview) is the route name; always prefix it with the module name. path may contain . Under requirements, an entry whose name matches a parameter (note_id: '\d+') is a regular expression restricting what the parameter may be. _permission is an access requirement and is mandatory: Drupal refuses routes with no access requirement.

Other access requirements: _role: 'editor', _user_is_logged_in: 'TRUE', _entity_access: 'node.update', _custom_access: '\Class::method', and _access: 'TRUE' for fully public pages.

Node.js Stand-in: a tiny router with parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

/notes/abc fails because the requirement \d+ rejects it: Drupal would return 404, and your controller is never called with bad input.

The controller

PHP
<?php

namespace Drupal\tutorial_notes\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;

class NotesController extends ControllerBase {

  public function overview(): array {
    $rows = [];
    foreach ($this->notes() as $id => $title) {
      $rows[] = [
        $this->t('Note @id', ['@id' => $id]),
        [
          'data' => [
            '#type' => 'link',
            '#title' => $title,
            '#url' => Url::fromRoute('tutorial_notes.view', ['note_id' => $id]),
          ],
        ],
      ];
    }
    return [
      '#type' => 'table',
      '#header' => [$this->t('ID'), $this->t('Title')],
      '#rows' => $rows,
      '#empty' => $this->t('No notes yet.'),
      '#cache' => ['tags' => ['tutorial_notes_list']],
    ];
  }

  public function view(int $note_id): array {
    $notes = $this->notes();
    if (!isset($notes[$note_id])) {
      throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }
    return ['#markup' => '<p>' . $notes[$note_id] . '</p>'];
  }

  public function title(int $note_id): string {
    return (string) ($this->notes()[$note_id] ?? $this->t('Note'));
  }

  private function notes(): array {
    return [1 => 'Plan the sprint', 2 => 'Write the module'];
  }

}

Points to notice:

  • A controller returns a render array (a nested PHP array with # properties), not HTML. Drupal renders it through the theme layer, handles caching and lets other modules alter it. Returning a Response object (for JSON, files, redirects) is also allowed.
  • Method arguments are matched by name to route parameters. Type hints convert values: int $note_id receives an integer.
  • Throw NotFoundHttpException for a missing item and AccessDeniedHttpException for forbidden access.
  • Use Url::fromRoute() and $this->t() instead of hard-coded paths and strings.
  • ControllerBase gives helpers such as $this->currentUser(), $this->entityTypeManager() and $this->config(). For anything heavier use dependency injection (services).

Parameter upcasting

Drupal can turn a parameter into an object. For a route like /notes/{node} with a type: entity:node option, the controller receives a loaded NodeInterface:

YAML
tutorial_notes.node_summary:
  path: '/notes/{node}/summary'
  defaults:
    _controller: '\Drupal\tutorial_notes\Controller\NotesController::summary'
  requirements:
    _entity_access: 'node.view'
  options:
    parameters:
      node:
        type: entity:node

Drupal returns 404 if the node does not exist and checks view access for you.

JSON responses

PHP
use Symfony\Component\HttpFoundation\JsonResponse;

public function api(): JsonResponse {
  return new JsonResponse(['notes' => array_values($this->notes())]);
}

For cacheable JSON use CacheableJsonResponse and add cache metadata.

Make a page reachable from a menu with tutorial_notes.links.menu.yml:

YAML
tutorial_notes.overview:
  title: 'Notes'
  route_name: tutorial_notes.overview
  menu_name: main
  weight: 10

Local tasks (tabs) go in tutorial_notes.links.task.yml, and buttons such as "Add note" in tutorial_notes.links.action.yml. All use route names, so if you change a path the links follow.

Node.js Stand-in: generate a URL from a route name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must every route have in its requirements?

    Drupal requires an access check so a route can never be accidentally public.
  2. 2. What should a typical controller return?

    Render arrays integrate with theming, caching and alter hooks.
  3. 3. What does the requirement note_id with value \d+ do?

    Requirements named after parameters are regular expressions on that parameter.
  4. 4. Why use Url::fromRoute() instead of a hard-coded path?

    Route names are stable; paths may be changed by site builders or modules.

Summary

  • Routes live in MODULE.routing.yml; names are prefixed by the module.
  • Every route needs an access requirement; parameters can be restricted by regex or upcast to entities.
  • Controllers return render arrays (or Response objects) and throw HTTP exceptions for errors.
  • Menu links, tabs and actions are separate YAML files that point to route names.
  • Generate URLs with Url::fromRoute().

Next: Hooks and Event Subscribers