How to get parent taxonomy title in Drupal 8

I used the following to get the parent of the taxonomy term in drupal 8:

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

$parent = reset($parent);

Now that I have a parent, how can I get a parent from it?

+4
source share
2 answers

Now that you have the term parent with code:

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

$parent = reset($parent);

You can simply use the method $parent->id()to get the parent tid.

+2
source

You can pull out the tree for the dictionary and sift it.

// 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;
  }
}
0
source

Source: https://habr.com/ru/post/1625213/


All Articles