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);

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook