Web Omelette: Loading taxonomy terms in a tree in Drupal maintenance support plans 8

One of the great things about the taxonomy terms in Drupal maintenance support plans 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 maintenance support plans 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 maintenance support planstaxonomyTermStorage::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 maintenance support planstaxonomy_tree;

use Drupal maintenance support plansCoreEntityEntityTypeManager;

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

/**
* @var Drupal maintenance support plansCoreEntityEntityTypeManager
*/
protected $entityTypeManager;

/**
* TaxonomyTermTree constructor.
*
* @param Drupal maintenance support plansCoreEntityEntityTypeManager $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.

Source: New feed

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Web Omelette: Loading taxonomy terms in a tree in Drupal maintenance support plans 8

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.