【问题标题】:How do I get the parent tid of a taxonomy term in Drupal 8如何在 Drupal 8 中获取分类术语的父 tid
【发布时间】:2016-04-26 22:39:56
【问题描述】:

我使用以下内容在 drupal 8 中获取分类术语的父项:

$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);

$parent = reset($parent);

现在我有了父级,我如何从中获取父级 tid?

【问题讨论】:

  • 由于 $parent 是由术语 id 键入的父术语数组,因此我使用 reset(array_keys($parent)) 如果有更好的方法,请告诉我。
  • 目前loadParents() 似乎是唯一的选择,但可以在drupal.org/node/2543726 中添加$term->parent->target_id 支持
  • 您的 $parent 变量包含一个 Term 对象。您应该使用$parent->id() 方法来获取它的tid。
  • array_key_first 将为您提供关键字 id

标签: drupal-8


【解决方案1】:

现在您有了带有代码的术语“父级”:

$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);

$parent = reset($parent);

您可以简单地使用$parent->id() 方法来获取您的父母tid

$parent_tid = $parent->id()

【讨论】:

  • 那一直都在吗?我不知道我是怎么错过的。谢谢。
  • 我该如何实现这个?这是否进入主题 preprocess_node.我可以从中创建一个变量,以便我可以在树枝模板中使用该变量吗?
  • 是的,您可以在大多数可用的预处理中使用preprocess_nodepreprocess_pagepreprocess_themepreprocess_route 等。
【解决方案2】:
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term_id);
$parent_term_id = $term->parent->target_id;

如果存在,它将提供术语的父 ID。

【讨论】:

    【解决方案3】:

    您可以拉出词汇树并进行筛选。

    // assuming $termId is the child tid..
    $tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('VOCABULARY_NAME', 0);
    for ($tree as $term) {
      if (in_array($termId, $term->parents)) {
        $parent_term = $term;
        break;
      }
    }
    

    【讨论】:

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