Sep 22, 2020 in Drupal 8, Snippets

A common case when using facet searches is where you want to list some terms and when people click on them you get redirected to a filtered view. This code helps you with that. 

First, create a custom module, and inside that a file called mymodule.services.yml. Inside place this snippet. 

services:
  MYMODULE.event_subscriber:
    class: Drupal\MYMODULE\EventSubscriber\CustomRedirects
    tags:
      - {name: event_subscriber}

Now add a file to MYMODULE\src\EventSubscriber called CustomRedirects.php with the following code. You'll see we are redirecting tag view of certain vocabularies to a specified views page with the correct tag selected. Make sure the module is enabled and cache is cleared!

<?php

namespace Drupal\MYMODULE\EventSubscriber;

use Drupal\taxonomy\Entity\Term;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class CustomRedirects
 * @package Drupal\MYMODULE\EventSubscriber
 *
 * Redirects tags to the projects page with correct filter enabled
 */
class CustomRedirects implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {

    $request = $event->getRequest();
    $path = $request->getRequestUri();
    if((strpos($path, 'taxonomy/term') !== false) && (strpos($path, '/edit') === false) && (strpos($path, '/delete') === false)) {
      // Redirect tags to project page
      $id = preg_replace("/[^0-9]/", "", $path);
      $term = Term::load($id);
      $vocabulary_id = $term->getVocabularyId();
      $newPath = false;
      switch($vocabulary_id) {
        case 'sector':
          $newPath = '/projecten/overzicht?f[0]=sectors%3A'.$id;
          break;
        case 'subsidy_framework':
          $newPath = '/projecten/overzicht?f[0]=subsidy_frameworks%3A'.$id;
          break;
        case 'application':
          $newPath = '/projecten/overzicht?f[0]=applications%3A'.$id;
          break;
      }

      if($newPath) {
        $new_response = new RedirectResponse($newPath, '301');
        $new_response->send();
      }

    }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    //The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:
    $events[KernelEvents::REQUEST][] = array('checkForRedirection', 29);
    return $events;
  }

}