Last active
November 19, 2021 14:12
-
-
Save levmyshkin/6e9ed6748ed417b7cb37c73a5347eb4d to your computer and use it in GitHub Desktop.
Drupal Event Dispatcher redirect programmatically
This file contains 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: | |
drupalbook_examples.event_subscriber: | |
class: Drupal\drupalbook_examples\EventSubscriber\DrupalbookExamplesSubscriber | |
tags: | |
- {name: event_subscriber} |
This file contains 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 | |
// modules/custom/drupalbook_examples/src/EventSubscriber/DrupalbookExamplesSubscriber.php | |
namespace Drupal\drupalbook_examples\EventSubscriber; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class DrupalbookExamplesSubscriber implements EventSubscriberInterface { | |
public function checkForRedirection(GetResponseEvent $event) { | |
if ($event->getRequest()->query->get('redirect-me')) { | |
$event->setResponse(new RedirectResponse(\Drupal::url('<front>', [], ['absolute' => TRUE]))); | |
} | |
} | |
public function redirectBeforeWithoutCache(GetResponseEvent $event) { | |
if ($event->getRequest()->query->get('redirect-me')) { | |
$event->setResponse(new RedirectResponse(\Drupal::url('<front>', [], ['absolute' => TRUE]))); | |
} | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function getSubscribedEvents() { | |
$events[KernelEvents::REQUEST][] = array('checkForRedirection'); | |
$events[KernelEvents::REQUEST][] = array('redirectBeforeWithoutCache', 300); | |
return $events; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment