0
namespace Drupal\project_extras\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 RedirectAnonymousSubscriber implements EventSubscriberInterface {


  public static function getSubscribedEvents() {
    // This announces which events you want to subscribe to.
    // We only need the request event for this example.  Pass
    // this an array of method names
    return([
      KernelEvents::REQUEST => [
        ['redirectMyContentTypeNode'],
      ]
    ]);
  }


  /**
   * Redirect requests for my_content_type node detail pages to node/123.
   *
   * @param GetResponseEvent $event
   * @return void
   */

  public function redirectMyContentTypeNode(GetResponseEvent $event) {

    $request = $event->getRequest();

    // This is necessary because this also gets called on
    // node sub-tabs such as "edit", "revisions", etc.  This
    // prevents those pages from redirected.
    if ($request->attributes->get('_route') !== 'entity.node.canonical') {
      return;
    }

    // Only redirect a certain content type.
    if ($request->attributes->get('node')->getType() !== 'specific_content_type') {
      return;
    }

    // This is where you set the destination.
    $redirect_url = Url::fromUri('entity:node/10');
    $response = new RedirectResponse($redirect_url->toString(), 301);
    $event->setResponse($response);
  }
}
0

You can load a user and check for authentication

$currentUser = \Drupal::currentUser();

// Do nothing if the user is authenticated.
if ($currentUser->isAuthenticated()) {
  return;
}
  • How can i add multiple content types? How can i create array? – Denis Omerovic Jun 5 '17 at 17:40
  • You can refer to this article enzolutions.com/articles/2015/12/03/… for getting list of all content type – Akash Jain Jun 5 '17 at 17:46
  • I don't want all content types. I'm tryin to create array so i can specify content type. This is how i will do just for one content type if ($request->attributes->get('node')->getType() !== 'one_content_type') { return; } – Denis Omerovic Jun 5 '17 at 17:54
  • You can try this code $current_content_type = $request->attributes->get('node')->getType(); $contentTypes = \Drupal::service('entity.manager')->getStorage('node_type')->loadMultiple(); $contentTypesList = []; foreach ($contentTypes as $contentType) { $contentTypesList[$contentType->id()] = $contentType->label(); } if (in_array($current_content_type, $contentTypesList)) { return; } – Akash Jain Jun 5 '17 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.