【问题标题】:Getting Taxonomy Terms for a Node ID in Drupal 8在 Drupal 8 中获取节点 ID 的分类术语
【发布时间】:2018-04-27 16:13:15
【问题描述】:

我正在尝试添加一个预处理钩子,以将基于分类名称的类添加到我的 drupal 安装的主体 css。通过四处搜索和反复试验,我设法获取了有关节点的所有信息,但我想将其带到下一步,并根据特定节点 ID 获取所有分类术语。

我目前的预处理代码如下:

function custom_preprocess_html(&$variables) {
// Add the node ID and node type to the body class

$body_classes = [];
$nodeFields =\Drupal::service('current_route_match')->getParameter('node')->toArray();

if (is_array($nodeFields) && count($nodeFields) > 0) {
    if (isset($nodeFields['nid'])) {
        $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
    }
    if (isset($nodeFields['type'])) {
        $body_classes[] = $nodeFields['type'][0]['target_id'];
    }
}

$variables['attributes']['class'] = $body_classes;
}

它工作正常并下拉有关节点的信息。根据here 的答案,似乎我所要做的就是添加以下行来获取分类术语:$taxonomyTerms = $nodefields->get('field_yourfield')->referencedEntities(); 但是当我这样做时,Drupal 会抛出一个错误。我会坦率地承认我是 Drupal 8 的新手,所以任何关于我哪里出错的建议(可能是 field_yourfield 不存在吗?)将不胜感激。

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

    如果您尝试获取引用的术语名称并将它们添加为主体类,那么您的方法似乎有点偏离。

    这是我用的:

    function CUSTOM_preprocess_html(&$variables) {
      // Entity reference field name.
      $field_name = 'field_tags';
      // Get the node object from the visited page. 
      // If the page is not a node detail page, it'll return NULL.
      $node = \Drupal::request()->attributes->get('node');
    
      // Let's make sure the node has the field.
      if ($node && $node->hasField($field_name)) {
        $referenced_entities = $node->get($field_name)->referencedEntities();
        foreach ($referenced_entities as $term) {
          $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($term->getName());
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2017-03-19
      • 2022-06-23
      • 1970-01-01
      相关资源
      最近更新 更多