How to create a redirect event subscriber in Drupal 8

Public

You have a node type. You want to serve that node type in blocks only. So, you need to disallow the node view page. To do that, you need to create an event subscriber, redirecting you to another page when the condition is met (Front Page in our case).

</> CopyGet raw version
php
  1. File name: my_module.services.yml
  2. services:
  3. my_module.event_subscriber:
  4. class: Drupal\my_module\EventSubscriber\MymoduleSubscriber
  5. tags:
  6. - {name: event_subscriber}
  7.  
  8. File name: src/EventSubscriber/MyModuleSubscriber.php
  9. <?php
  10. namespace Drupal\mymodule\EventSubscriber;
  11.  
  12. use Drupal;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17.  
  18. class MyModuleSubscriber implements EventSubscriberInterface {
  19.  
  20. public function checkForRedirection(GetResponseEvent $event) {
  21.  
  22. $poll = \Drupal::routeMatch()->getParameter('node');
  23. if (!empty($node) && $node->getType() == 'node_type') {
  24. $url = \Drupal::getContainer()->get('url_generator')->generateFromRoute('<front>');
  25. $event->setResponse(new RedirectResponse($url, 301));
  26. }
  27.  
  28. }
  29.  
  30. /**
  31.   * {@inheritdoc}
  32.   */
  33. public static function getSubscribedEvents() {
  34. $events[KernelEvents::REQUEST][] = array('checkForRedirection');
  35.  
  36. return $events;
  37. }
  38. }
  39. ?>