Last active
June 17, 2021 12:55
-
-
Save crittermike/4a796bddfe42afdf727094b0473449b6 to your computer and use it in GitHub Desktop.
Example of overriding a route controller in Drupal 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
example_module.route_subscriber: | |
class: Drupal\example_module\Routing\RouteSubscriber | |
tags: | |
- { name: event_subscriber } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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', | |
)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!