William A Hopkins
William A Hopkins

Reputation: 113

How do I get the parent tid of a taxonomy term in Drupal 8

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

Answers (3)

valdeci
valdeci

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

Vishnu Vijaykumar
Vishnu Vijaykumar

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

Xandor
Xandor

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

Related Questions