Skip to content

Instantly share code, notes, and snippets.

@lcube45
Created June 1, 2020 14:54
Show Gist options
  • Save lcube45/b634852c51ec100be64433a211e34e3a to your computer and use it in GitHub Desktop.
Save lcube45/b634852c51ec100be64433a211e34e3a to your computer and use it in GitHub Desktop.
Drupal 8 - récupérer l'arborescence des termes
<?php
namespace Drupal\mon_module\Tools
use Drupal\taxonomy\Entity\Term;
/**
* Service de récupération d'arborescence de termes
*
* @package Drupal\mon_module\Tools
*/
class IteratifService {
/**
* Load Vocabulary Tree.
*
* @param string $vid
* Vocabulary ID to retrieve terms for.
* @param int $parent
* The term ID under which to generate the tree.
* @param int $max_depth
* The number of levels of the tree to return.
*
* @return array
* Return array
*/
public function loadVocabularyTree($vid, $parent = 0, $max_depth = NULL) {
// Get tree.
/** @var \Drupal\taxonomy\TermStorage $taxonomy_storage */
$taxonomy_storage = \Drupal::service('entity_type.manager')
->getStorage('taxonomy_term');
$taxonomy = $taxonomy_storage->loadTree($vid, $parent, $max_depth, FALSE);
// Get terms of the passed vid.
$terms = $taxonomy_storage->loadByProperties(['vid' => $vid]);
// Init result array.
$result = [];
foreach ($taxonomy as $taxo) {
if ($taxo->depth == 0) {
$result[$taxo->tid] = $terms[$taxo->tid];
}
else {
foreach( $taxo->parents as $parentId ){
if ($parentId != 0 && array_key_exists($parentId, $terms)) {
if (!is_array($terms[$parentId]->children)) {
$terms[$parentId]->children = [];
}
$terms[$parentId]->children[$taxo->tid] = $terms[$taxo->tid];
}
}
}
}
return $result;
}
}
@lcube45
Copy link
Author

lcube45 commented Jun 1, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment