2

I have a vocabulary (Vehicle) which contains the following taxonomy terms.

  • Maruti
    • Alto
    • Swift
    • Baleno
    • Barazza
  • Hundai
    • I10
    • I20
    • Creta
  • Tata
    • Nexon
    • Safari
    • Nano

I want to get only the parent taxonomy terms: Maruti, Hundai, and Tata.

I tried the following code, but it doesn't return the expected values.

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

Also the following code didn't work for me.

$parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadAllParents('termid');
2
  • Are you aware that Drupal 8 reached end of life on November 2 2021? I have been asking this of people who are doing new work on Drupal 8 because there is nothing more important than upgrading to Drupal 9.
    – mona lisa
    Jun 21, 2022 at 12:40
  • Yes i know D8 is reached end of life
    – abc
    Jun 21, 2022 at 12:50

1 Answer 1

2

The methods you are mentioning accept as argument a term ID and return parents of this term.

You can use loadTree() providing the vocabulary name and for the second argument 0 to load the entire tree, but only for one level (third argument):

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')->loadTree('vehicle', 0, 1, TRUE);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.