Created
June 1, 2020 14:54
-
-
Save lcube45/b634852c51ec100be64433a211e34e3a to your computer and use it in GitHub Desktop.
Drupal 8 - récupérer l'arborescence des termes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Construction de l'arbre de manière itérative (plus performante) vs manière récursive :