0

我有一个场景,我需要对未找到的 url 执行一些重定向

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

通过我正在使用的插件添加了单词搜索,它是前端路由而不是后端,因此在刷新此 url 时,我得到Not Found,这完全有道理我需要做的是从 URL 中删除单词 search 并重定向到,

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

由于搜索是一个常用词,可以在其他内容类型中使用,我首先需要检查 URL 是否属于我的自定义内容类型。让我向您展示我已经拥有的一个实现。

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

所以在这里我正在做的是用我的内容类型抓取所有节点,并从 URI 中抓取 Nid 并匹配它们,这确实有效,但还有另一个问题。在页面属性中,我们有一个ALias选项,所以如果用户使用自定义别名,那么我不再在 URI 中获得Nid,所以这个逻辑会中断,

这个问题可能看起来有点棘手,但要求很简单。我正在寻找一个统一的解决方案来将 URL 解析为一些 drupal API 并简单地获取内容类型名称。Url 可能包含自定义别名或 Nid

4

1 回答 1

3

您可以创建一个EventSubscriber订阅事件kernel.request来处理 URL 的情况<node URL>/search

有关创建的详细步骤EventSubscriber,您可以在此处查看

以下是您需要在EventSubscriber课堂上添加的内容:

请求订阅者.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
      }
    }
  }
}

于 2021-03-31T03:10:17.023 回答