Skip to content

Instantly share code, notes, and snippets.

@levmyshkin
Last active November 19, 2021 14:12
Show Gist options
  • Save levmyshkin/6e9ed6748ed417b7cb37c73a5347eb4d to your computer and use it in GitHub Desktop.
Save levmyshkin/6e9ed6748ed417b7cb37c73a5347eb4d to your computer and use it in GitHub Desktop.
Drupal Event Dispatcher redirect programmatically
services:
drupalbook_examples.event_subscriber:
class: Drupal\drupalbook_examples\EventSubscriber\DrupalbookExamplesSubscriber
tags:
- {name: event_subscriber}
<?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