Need some help with your project? Contact me

Loading taxonomy terms in a tree in Drupal 8

One of the great things about the taxonomy terms in Drupal has always been their hierarchical readiness. That is, how they can easily be organised in a parent-child relationship via a simple drag-and-drop interface. This feature becomes even more important in Drupal 8 where creating entities for anything you want has become easy so we no longer have to (ab)use taxonomy term entities for everything. Unless, of course, we need this kind of behaviour.

However, I recently noticed a shortcoming in the way we are able to load taxonomy terms programatically. I needed to load a tree of terms as represented by their hierarchy. But there is no API (for the moment) that allows me to do so. At least none that I could find.

What I needed was similar to the menu system where if you load a tree, you get an array of MenuLinkTreeElement objects that wrap the links and which can each contain an array of MenuLinkTreeElement objects that represent the children (subtree) of that link. So one big multidimensional array of objects.

For terms, I imaged there would be something similar, but I was wrong. The Drupal\taxonomy\TermStorage::loadTree() method basically does half the job I want. It returns all the terms in the vocabulary, each represented as a stdClass object (why?) that contains some basic info. And in this object we get a parents array that contains the IDs of the terms which are its parents (as you know, terms can have multiple parents).

This may be enough in certain cases. However, I wanted to go one step further. So I created a simple service that loads the tree of a vocabulary in a multidimensional array, similar to what the menu system does:


    namespace Drupal\taxonomy_tree;

    use Drupal\Core\Entity\EntityTypeManager;

     * Loads taxonomy terms in a tree
    class TaxonomyTermTree {

       * @var \Drupal\Core\Entity\EntityTypeManager
      protected $entityTypeManager;

       * TaxonomyTermTree constructor.
       * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
      public function __construct(EntityTypeManager $entityTypeManager) {
        $this->entityTypeManager = $entityTypeManager;

       * Loads the tree of a vocabulary.
       * @param string $vocabulary
       *   Machine name
       * @return array
      public function load($vocabulary) {
        $terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadTree($vocabulary);
        $tree = [];
        foreach ($terms as $tree_object) {
          $this->buildTree($tree, $tree_object, $vocabulary);

        return $tree;

       * Populates a tree array given a taxonomy term tree object.
       * @param $tree
       * @param $object
       * @param $vocabulary
      protected function buildTree(&$tree, $object, $vocabulary) {
        if ($object->depth != 0) {
        $tree[$object->tid] = $object;
        $tree[$object->tid]->children = [];
        $object_children = &$tree[$object->tid]->children;

        $children = $this->entityTypeManager->getStorage('taxonomy_term')->loadChildren($object->tid);
        if (!$children) {

        $child_tree_objects = $this->entityTypeManager->getStorage('taxonomy_term')->loadTree($vocabulary, $object->tid);

        foreach ($children as $child) {
          foreach ($child_tree_objects as $child_tree_object) {
            if ($child_tree_object->tid == $child->id()) {
             $this->buildTree($object_children, $child_tree_object, $vocabulary);

No need to copy it from here, you can find it in this repository inside a simple module called taxonomy_tree.

So what I basically do here is load the default tree and iterate through all the objects. If any of them are not already at the bottom of the tree, I populate a children key with their children. This happens by using the TermStorage::loadChildren() method and recursing through that list as well.

So let me know what you think and if this helps you out.


Hi, Danny,
Thanks for this effort to solve a common problem
Would you post an example of using this class?
Is it $tree = TaxonomyTermTree::load( 'machine_name' );

I am getting error:
Fatal error: Call to a member function getStorage() on null in ....../modules/contrib/taxonomy_tree/src/TaxonomyTermTree.php on line 35


No, that is not a static method so cannot be called statically. This class is what you would register as a service with the EntityTypeManager as a dependency.

Thanks, Danny for your quick response.

This really doesn't help me however. I am not finding documentation on the use of EntityTypeManager() and I obviously don't know how to use it.
I am trying
$etm = new EntityTypeManager( 'taxonomy' );
$tt = new TaxonomyTermTree( $etm );;
$tree = TaxonomyTermTree::load( 'machine_name' );

and get Error: Argument 1 passed to Drupal\Core\Entity\EntityTypeManager::__construct() must implement interface Traversable,

Would you be able to provide an example using your TaxonomyTermTree?

Thanks again.

Usage example

$tt = \Drupal::service('taxonomy_tree.taxonomy_term_tree');     
 $tree = $tt->load('services');

I'm still new to services and dependency injection, in this case, I can load the service statically; but this doesn't work

private $termTree;

   * @param \Drupal\taxonomy_tree\TaxonomyTermTree $termTree
   *    KeywordsIndexController constructor.
  public function __construct(TaxonomyTermTree $termTree) {
    $this->termTree = $termTree;

Using drupal console to debug, I get

You have requested a non-existent service "taxonomy_tree.taxonomy_term_tree".

so I must be missing a crucial part of registering the service. I should mention that I'm using the module directly, complete with

You can actually load entity with loadTree. You just need to set last parameter to TRUE. This may help you as a shortcut in your function..

$vocabulary_entities = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('vocablary_id', 0, NULL, TRUE);

I'm hoping this solution solves my need to show a select field with hierarchy on the content adding page, using a custom widget. But implementing this, seems to be above my skill level. I installed the module, and tried to do it like this:

    $tt = Drupal::service('taxonomy_tree.taxonomy_term_tree');
    $tree = $tt->load('plant_part');

$element['plant_part_described'] = array(
        '#type' => 'select',
        '#options' => $tree,
        '#title' => t('title'),
        '#size' => 1,       
        '#default_value' => isset($items[$delta]->plant_part_described) ? $items[$delta]->plant_part_described : NULL,

I also tried adding at the top of the file: use Drupal\taxonomy_tree;

Maybe I just don't know how to include services...


Hi I just install this plugin and want to acsses the tree in a variable so i just write this code in module file
function taxonomy_tree_preprocess_page(&$variables) {
$tt = \Drupal::service('taxonomy_tree.taxonomy_term_tree');
$trr = load('file_folders');
i got error Error: Call to undefined function load() in taxonomy_tree_preprocess_page() (line 21 of modules\taxonomy_tree-master\taxonomy_tree.module).
plez suggest

Add new comment

You must have Javascript enabled to use this form.