Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Loading taxonomy terms in a tree in Drupal 8

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web