Altering the existing routes in Drupal 8

Sometimes we need to do it. In Drupal 7 it was possible through hook_menu_alter. Let's sort out how to do it in Drupal 8.

Primarily create the class for Route Subscriber. It has to be located in YOUR_MODULE/src/Routing/RouteSubscriber.php

Let's try to alter the access callback:

<?php

/**
 * @file
 * Contains \Drupal\my_module\Routing\RouteSubscriber.
 */

namespace Drupal\my_module\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) {
    if ($route_item = $collection->get('my_route')) {
      $requirements = $route_item->getRequirements();
      unset($requirements['_permission']);
      $requirements['_custom_access'] = '\Drupal\my_module\Access\MyModuleAccessCheck::AllowToSeeContent';
      $route_item->setRequirements($requirements);
    }
  }
}

Here we will remove the access checking by permission and use our own access checking.

To enable your RouterSubscriber, you should define it in my_module.services.yml

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

As you can see, it's pretty easy.

 

Tags: