I want to redirect to a specific URL in an EventSubscriber
class instead of showing the Page not found page. I followed Symfony2 redirect for event listener? but the redirect goes to the home.
This is the code I am using.
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PageNotFound implements EventSubscriberInterface {
public function pageNotFound(GetResponseEvent $event) {
$request = $event->getRequest();
$id = '1234';
$scheme_and_http_host = $request->getSchemeAndHttpHost();
$url = Url::fromRoute('myroute', ['id' => $id])->toString(); // this url exist (checked)
$response = new RedirectResponse($scheme_and_http_host . $url, Response::HTTP_MOVED_PERMANENTLY);
$event->setResponse($response);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['pageNotFound'];
return $events;
}
}
mymodule.services.yml
services:
mymodule.page_not_found:
class: Drupal\mymodule\EventListener\PageNotFound
tags:
- {name: event_subscriber}
How do I redirect users from an EventSubscriber
class?