Skip to content

Instantly share code, notes, and snippets.

@DanLaufer
Created October 19, 2018 17:16
Show Gist options
  • Save DanLaufer/1959e2726de1afede7aa3fa14a6d8029 to your computer and use it in GitHub Desktop.
Save DanLaufer/1959e2726de1afede7aa3fa14a6d8029 to your computer and use it in GitHub Desktop.
Drupal 8 - Module to redirect content type nodes to the homepage
// redirect_nodes.info.yml
name: Redirect Nodes
type: module
description: Redirect nodes that shouldn't be accessed.
package: Custom
core: 8.x
configure: mytheme.checkForRedirection
services:
redirect_nodes.redirectMyContentType:
class: Drupal\redirect_nodes\EventSubscriber\RedirectNodesSubscriber
tags:
- { name: event_subscriber }
// file at src/EventSubscriber/RedirectNodesSubscriber.php
<?php
/**
* @file
* Contains \Drupal\redirect_nodes\EventSubscriber\RedirectNodesSubscriber
*/
namespace Drupal\redirect_nodes\EventSubscriber;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RedirectNodesSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return([
KernelEvents::REQUEST => [
['redirectMyContentTypeNode'],
]
]);
}
/**
* Redirect requests for nodes to <front>.
*
* @param GetResponseEvent $event
* @return void
*/
public function redirectMyContentTypeNode(GetResponseEvent $event) {
$request = $event->getRequest();
// Prevent redirecting on node's "edit", "revisions", etc. pages.
if ($request->attributes->get('_route') !== 'entity.node.canonical') {
return;
}
// Prevent redirect on all content types other than specified here.
if ($request->attributes->get('node')->getType() !== 'content_type_1' &&
$request->attributes->get('node')->getType() !== 'content_type_2'
) {
return;
}
// This is where you set the destination.
$redirect_url = Url::fromUri('internal:/');
$response = new RedirectResponse($redirect_url->toString(), 301);
$event->setResponse($response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment