Jan 02, 2020 in Drupal 8, Snippets

Sometimes simple tasks like changing a page title of a system page can be hard. Luckily, drupal 8 provides clean ways to do that. In this tutorial some info about RouteSubscribers.

First, add the file RouteSubscriber.php to a src/Routing folder. Add the following:

<?php
namespace Drupal\MYMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    /** @var Route $entityUserEditForm */
    $entityUserEditFormRoute = $collection->get('entity.user.edit_form');

    if ($entityUserEditFormRoute) {
      $entityUserEditFormRoute->setDefaults([
        '_entity_form' => 'user.default',
        '_title' => 'Edit my profile',
      ]);
    }
  }

}

So this is like the last "call" that decides what is shown on this route. In the file above we decide to keep showing the standard user form, but to update the title.

Next, we should register the routeSubscriber by adding it to the services.yml file of this module:

services:
  MYMODULE.route_subscriber:
    class: Drupal\MYMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Clear cache and you are all done!

Credits to this post on Stackexchange: https://drupal.stackexchange.com/a/261272