Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

In this tuto, I'll show you how to load Taxonomy Terms by Level in drupal 8. using 

loadTree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) function.

Parameters

string $vid: Vocabulary ID to retrieve terms for.

int $parent: The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.

int $max_depth: The number of levels of the tree to return. Leave NULL to return all levels.

bool $load_entities: If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

Get only the 1st level

$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('tags', 0, 1, TRUE);
$result = [];
foreach ($tree as $term) {
  $result[] = $term->get('name')->value;
}
kint($result);

Get the 1st and 2nd levels

$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('tags', 0, 2, TRUE);
$result = [];
foreach ($tree as $term) {
  $result[] = $term->get('name')->value;
}
kint($result);

Get only the 2nd level

$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, 2, TRUE);
$result = [];
foreach ($tree as $term) {
  if (!empty($manager->loadParents($term->id()))) {
    $result[] = $term->get('name')->value;
  }
}
kint($result);

Get the 2nd and 3rd levels

$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, 3, TRUE);
$result = [];
foreach ($tree as $term) {
  if (!empty($manager->loadParents($term->id()))) {
    $result[] = $term->get('name')->value;
  }
}
kint($result);

Get only the last level

$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, NULL, TRUE);
$result = [];
foreach ($tree as $term) {
  if (empty($manager->loadChildren($term->id()))) {
    $result[] = $term->get('name')->value;
  }
}
kint($result);

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon