Search code examples
drupaldrupal-9

API to get a content type against URL


I have a scenario where I need to perform some redirection of a not found url

http://localhost/drupal9/node/1/search

the word search is added though a plugin I am using and it is a front-end route not a backend so upon refreshing this url I get Not Found which totally makes sense what I need to do is remove the word search from the URL and redirect to,

http://localhost/drupal9/node/1/

as search is a common word and can be used in other content type I first need to check whether the URL is of my custom content type. let me show you a piece of implementation I already have.

function [module]_preprocess_page(&$variables) {
  $query = \Drupal::entityQuery('node')
  ->condition('type', [module]);
$nids = $query->execute();
if(array_search(2,$nids)){
echo "yes";
}
}

so over here what I am doing is grabbing all the nodes with my content type and grabbing the Nid from URI and matching them and this does work but there is another problem with this. In the page properties we have an option of ALias so if the user uses a custom alias, then I dont get the Nid in the URI anymore so this logic breaks,

the question may seem a bit tricky but the requirement is simple.I am looking for a unified solution to parse the URL into some drupal API and simply getting back the content type name.The Url may contain a custom alias or a Nid


Solution

  • You can create an EventSubscriber subscribing the event kernel.request to handle the case of URL <node URL>/search.

    For detailed steps to create an EventSubscriber, you can see here.

    And below is what you need to put in your EventSubscriber class:

    RequestSubscriber.php

    <?php
    
    namespace Drupal\test\EventSubscriber;
    
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    /**
     * Class RequestSubscriber.
     */
    class RequestSubscriber implements EventSubscriberInterface {
    
      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        return [
          KernelEvents::REQUEST => 'onKernelRequest',
        ];
      }
    
      public function onKernelRequest($event) {
        $uri = $event->getRequest()->getRequestUri();  // get URI
        if (preg_match('/(.*)\/search$/', $uri, $matches)) {  // check if URI has form '<something>/search'
          $alias = $matches[1];
          $path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);  // try to get URL from alias '<something>'
          if (preg_match('/node\/(\d+)/', $path, $matches)) {  // if it is a node URL
            $node = \Drupal\node\Entity\Node::load($matches[1]);
            $content_type = $node->getType();
            //... some logic you need
          }
        }
      }
    }