11

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?

William A Hopkins
  • 113
  • 1
  • 1
  • 6
  • Since $parent is an array of parent terms keyed by the term id I went with `reset(array_keys($parent))` if there's a better way please let me know. – William A Hopkins Jan 21 '16 at 00:30
  • 1
    For now `loadParents()` seems the only option, but `$term->parent->target_id` support can be added in https://www.drupal.org/node/2543726 – Leksat Jul 09 '16 at 09:41
  • Your `$parent` variable contains a `Term` object. You should use the `$parent->id()` method to get its tid. – AngularChef Jul 28 '16 at 10:34
  • array_key_first will get you the key which is the term id – JFC Sep 24 '21 at 18:56

3 Answers3

12

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()
valdeci
  • 13,962
  • 6
  • 55
  • 80
  • Was that always there? I don't know how I missed it. Thanks. – William A Hopkins Nov 11 '17 at 10:51
  • How can I implement this? Does this go in theme preprocess_node. Can I create a variable from this so that I can use the variable in a twig template? – paul cappucci May 02 '18 at 14:01
  • yeah, you can use in most of the available preprocesses as `preprocess_node`, `preprocess_page`, `preprocess_theme`, `preprocess_route` and so on. – valdeci May 02 '18 at 14:09
4
$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.

Prashant Kanse
  • 772
  • 11
  • 23
1

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;
  }
}
Xandor
  • 11
  • 1