Reputation: 113
I used the following to get the parent of a taxonomy term in drupal 8:
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);
$parent = reset($parent);
Now that I have the parent how do I get the parent tid from that?
Upvotes: 11
Views: 26294
Reputation: 15237
Now that you have the term parent with the code:
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);
$parent = reset($parent);
You can simply use the $parent->id()
method to get your parent tid.
$parent_tid = $parent->id()
Upvotes: 12
Reputation: 450
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term_id);
$parent_term_id = $term->parent->target_id;
It will provide the parent id of the term if exist.
Upvotes: 3
Reputation: 11
You can pull the tree for the vocabulary and sift through that.
// 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;
}
}
Upvotes: 1