Skip to content

Instantly share code, notes, and snippets.

@gabesullice
Last active August 8, 2024 06:54
Show Gist options
  • Save gabesullice/96bdae1518d11bb4565e72c33ffcae4c to your computer and use it in GitHub Desktop.
Save gabesullice/96bdae1518d11bb4565e72c33ffcae4c to your computer and use it in GitHub Desktop.
Dynamically Redirecting Drupal 8 Node Pages
name: My Module
type: module
description: Example of how to dynamically redirect a node page
core: 8.x
package: Custom
services:
my_module.response_subscriber:
class: Drupal\my_module\EventSubscriber\ResponseSubscriber
arguments: ["@current_route_match"]
tags:
- { name: event_subscriber }
<?php
/**
* This file should live at my_module/src/EventSubscriber/ResponseSubscriber.php
*/
namespace Drupal\my_module\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\CacheableRedirectResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Class ResponseSubscriber.
*
* @package Drupal\my_module
*/
class ResponseSubscriber implements EventSubscriberInterface {
/**
* Drupal\Core\Routing\CurrentRouteMatch definition.
*
* @var Drupal\Core\Routing\CurrentRouteMatch
*/
protected $routeMatch;
/**
* Constructor.
*/
public function __construct(CurrentRouteMatch $current_route_match) {
$this->routeMatch = $current_route_match;
}
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events['kernel.response'] = ['handle'];
return $events;
}
/**
* This method is called whenever the kernel.response event is
* dispatched.
*
* @param GetResponseEvent $event
*/
public function handle(Event $event) {
$route_name = $this->routeMatch->getRouteName();
switch ($route_name) {
case 'entity.node.canonical':
$node = $this->routeMatch->getParameter('node');
if ($this->redirectApplies($node)) {
$event->setResponse($this->getRedirect($node));
}
}
}
/**
* Determines whether we should send a RedirectResponse for this node.
*/
protected function redirectApplies(NodeInterface $node) {
// One should have logic here returning TRUE or FALSE for whether we should redirect this response.
return TRUE;
}
protected function getRedirect(NodeInterface $node) {
$response = CacheableRedirectResponse::create($url);
$response->addCacheableDependency($node);
return $response;
}
}
@MatthieuScarset
Copy link

This issue is fixed now :)
We can uncomment the cache-related parts in getRedirect() method.

and thank you for this very helpful snippet @gabesullice 👏

@gabesullice
Copy link
Author

Updated. Thanks!

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