Skip to content

Instantly share code, notes, and snippets.

@crittermike
Last active June 17, 2021 12:55
Show Gist options
  • Save crittermike/4a796bddfe42afdf727094b0473449b6 to your computer and use it in GitHub Desktop.
Save crittermike/4a796bddfe42afdf727094b0473449b6 to your computer and use it in GitHub Desktop.
Example of overriding a route controller in Drupal 8
services:
example_module.route_subscriber:
class: Drupal\example_module\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
<?php
/**
* @file
* Contains \Drupal\example_module\Controller\ExampleModuleController.
*/
// THIS FILE BELONGS AT /example_module/src/Controller/ExampleModuleController.php
namespace Drupal\example_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* An example controller.
*/
class ExampleModuleController extends ControllerBase {
/**
* {@inheritdoc}
*/
public function content() {
$build = array(
'#type' => 'markup',
'#markup' => t('Hello World!'),
);
return $build;
}
}
<?php
/**
* @file
* Contains \Drupal\example_module\Routing\RouteSubscriber.
*/
// THIS FILE BELONGS AT /example_module/src/Routing/RouteSubscriber.php
namespace Drupal\example_module\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
// Replace "some.route.name" below with the actual route you want to override.
if ($route = $collection->get('some.route.name')) {
$route->setDefaults(array(
'_controller' => '\Drupal\example_module\Controller\ExampleModuleController::content',
));
}
}
}
@develCuy
Copy link

Example of what you can do with controller overrides:

https://steemit.com/drupal/@develcuy/adding-custom-contextual-links-to-a-views-page-in-drupal-8

You can add custom contextual links to any page, linking to any route you want. So powerful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment