Profile picture for user admin
Daniel Sipos
08 May 2017

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:

<?php

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) {
      return;
    }
    $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) {
      return;
    }

    $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.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Comments

Mary Edith 14 Nov 2017 03:04

example of use?

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

thanks

Daniel Sipos 14 Nov 2017 15:56

In reply to by Mary Edith (not verified)

No, that is not a static

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.

Mary Edith 14 Nov 2017 19:26

example of use?

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.

Dendroud 23 Jan 2018 20:00

Thanks!

Usage example

$tt = \Drupal::service('taxonomy_tree.taxonomy_term_tree');     
 $tree = $tt->load('services');
Steve 04 Jun 2019 18:59

In reply to by Dendroud (not verified)

This works, but...

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 taxonomy_tree.services.yml.

zanvidmar 30 Mar 2018 15:12

Drupal\taxonomy\TermStorage::loadTree() can return entities

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..

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21TermStorage.php/function/TermStorage%3A%3AloadTree/8.2.x

$vocabulary_entities = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('vocablary_id', 0, NULL, TRUE);
cs 27 May 2018 00:18

for a custom field - select?

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...

Suggestions?

Lalit 12 Dec 2018 14:52

Not getting the tree of mu taxonomy

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');
kint($trr);
die('here');
}
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

miksha 20 Jul 2019 05:47

for a custom field - select (response to cs)

Using cs's code as example this could be implemented like this:

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

$tags_tree = [];
foreach ($tree as $tree_item) {
  $tags_tree[$tree_item->tid] = $tree_item->name;
  if(!empty($tree_item->children)){
    foreach ($tree_item->children as $child_item){
      //add space and two dashes before child items
      $tags_tree[$child_item->tid] = ' -- ' . $child_item->name;
    }
  }
}

$element['plant_part_described'] = array(
  '#type' => 'select',
  '#options' => $tags_tree,
  '#title' => t('title'),
  '#size' => 1,
  '#default_value' => isset($items[$delta]->plant_part_described) ? $items[$delta]->plant_part_described : NULL,
  '#required' => TRUE,
);
Tom 22 Oct 2019 16:25

Ordering correctly based on the structure in the vocab overview

Hi, cool code, I have got the ordering working like this

<?php

namespace Drupal\taxonomy_tree;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityTypeManager;

/**
 * Loads taxonomy terms in a tree
 */
class TaxonomyTermTree
{

    /**
     * @var EntityTypeManager
     */
    protected $entityTypeManager;

    /**
     * TaxonomyTermTree constructor.
     *
     * @param EntityTypeManager $entityTypeManager
     */
    public function __construct(EntityTypeManager $entityTypeManager)
    {
        $this->entityTypeManager = $entityTypeManager;
    }

    /**
     * Loads the tree of a vocabulary.
     *
     * @param $vocabulary
     * @return array
     * @throws InvalidPluginDefinitionException
     * @throws PluginNotFoundException
     */
    public function load($vocabulary): array
    {
        $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
     * @throws InvalidPluginDefinitionException
     * @throws PluginNotFoundException
     */
    protected function buildTree(&$tree, $object, $vocabulary): void
    {
        if ($object->depth != 0) {
            return;
        }
        $key = 'tid_' . $object->tid;

        $tree[$key] = $object;
        $tree[$key]->children = [];
        $object_children = &$tree[$key]->children;

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

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

        uasort($tree, function ($a, $b) {
            return $a->weight <=> $b->weight;
        });
        uasort($object_children, function ($a, $b) {
            return $a->weight <=> $b->weight;
        });
    }
}

Al 05 Aug 2020 13:25

references

I can't understand how these references works

$object_children = &$tree[$object->tid]->children;

and then

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);
        }
      }
    }
Elin 22 Sep 2021 15:58

Simpler way

Hey Daniel, I have managed to make a more simpler service to get terms as a nested array.

It returns an array of taxonomy terms, with each term having an extra children property, which is an array of terms again having a children property.

/**
 * Class TaxonomyUtils
 */
class TaxonomyUtils {
  
  /**
   * @var \Drupal\taxonomy\TermStorage
   */
  protected $taxonomyStorage;

  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->taxonomyStorage = $entityTypeManager->getStorage('taxonomy_term');
  }

  /**
   * @param string $vocabulary
   * @param int $parent
   *
   * @return array
   */
  public function getTree(string $vocabulary, int $parent = 0) {
    $terms = $this->taxonomyStorage->loadTree($vocabulary, $parent, 1, TRUE);
    $tree = [];

    foreach ($terms as $term) {
      $term->children = $this->getTree($vocabulary, $term->id());
      $tree[$term->id()] = $term;
    }

    return $tree;
  }

}

my_module.services.yml

services:
  my_module.taxonomy_utils:
    class: Drupal\my_module\Utils\TaxonomyUtils
    arguments: [ '@entity_type.manager' ]

Add new comment