You are here

protected function TaxonomyTermTree::buildListTree in Organigrams 8

Same name and namespace in other branches
  1. 8.2 src/TaxonomyTermTree.php \Drupal\organigrams\TaxonomyTermTree::buildListTree()

Populates a tree array with list items given a taxonomy term tree object.

Parameters

array $items: The populated tree so far.

object $object: Contains a taxonomy term.

string $vocabulary: Contains the machine name of the vocabulary.

array $fields: Contains the fields to show for taxonomy terms.

1 call to TaxonomyTermTree::buildListTree()
TaxonomyTermTree::loadList in src/TaxonomyTermTree.php
Loads the tree of a vocabulary and puts it in an item list.

File

src/TaxonomyTermTree.php, line 159

Class

TaxonomyTermTree
Loads taxonomy terms in a tree.

Namespace

Drupal\organigrams

Code

protected function buildListTree(array &$items, $object, $vocabulary, array $fields) {

  // Stop if depth is not 0.
  if ($object->depth != 0) {
    return;
  }

  // Create the list item.
  $items[$object
    ->id()] = [
    '#markup' => $object
      ->getName(),
    '#wrapper_attributes' => [
      'field_o_item_id' => $object
        ->id(),
      'field_o_parent' => $object
        ->get('parent')->target_id,
      'field_o_text' => $object
        ->getName(),
    ],
    'children' => [],
  ];

  // Check if there are fields and iterate through them.
  if (!empty($fields)) {
    foreach ($fields as $field_name => $field_config) {

      // Get the field.
      $field = $object
        ->get($field_name)
        ->first();
      if (empty($field)) {
        continue;
      }

      // Get the field value.
      $field_value = $field
        ->getValue();
      if (empty($field_value['value'])) {
        continue;
      }

      // Add the field with value as attribute to the list item.
      $items[$object
        ->id()]['#wrapper_attributes'][$field_name] = $field_value['value'];
    }
  }

  // Load the children of this taxonomy term.
  $object_children =& $items[$object
    ->id()]['children'];
  $children = $this->entityTypeManager
    ->getStorage('taxonomy_term')
    ->loadChildren($object
    ->id());

  // Stop if no children are found.
  if (!$children) {
    return;
  }

  // Iterate through all children and recursively add them to the tree array.
  $child_tree_objects = $this->entityTypeManager
    ->getStorage('taxonomy_term')
    ->loadTree($vocabulary, $object
    ->id(), NULL, TRUE);
  foreach ($children as $child) {
    foreach ($child_tree_objects as $child_tree_object) {
      if ($child_tree_object
        ->id() == $child
        ->id()) {
        $this
          ->buildListTree($object_children, $child_tree_object, $vocabulary, $fields);
      }
    }
  }
}