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.
Daniel Sipos
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.
Comments
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
In reply to example of use? 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.
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.
Thanks!
Usage example
In reply to Thanks! 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
Using drupal console to debug, I get
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
.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
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:
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?
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
for a custom field - select (response to cs)
Using cs's code as example this could be implemented like this:
Ordering correctly based on the structure in the vocab overview
Hi, cool code, I have got the ordering working like this
references
I can't understand how these references works
and then
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 achildren
property.my_module.services.yml
Module with this functionality please?
Hi,
I am looking for a solution like this in Drupal 10.
To add terms on node pages, with treir lineage attached.
So for instance, I have a node related to a place in Amsterdam.
I would like to be able to add the following terms as regional information:
---North Holland
-----Amsterdam.
And with another node, for example in Rotterdam, add only:
---South Holland
-----Rotterdam
Can youi help me with this?
Greetings, Summit on drupal.org, Martijn
Add new comment