You are here

public function EntityTreeBuilder::loadTree in Entity Reference Tree Widget 2.x

Same name and namespace in other branches
  1. 8 src/Tree/EntityTreeBuilder.php \Drupal\entity_reference_tree\Tree\EntityTreeBuilder::loadTree()

Load all entities from an entity bundle for the tree.

Parameters

string $entityType: The type of the entity.

string $bundleID: The bundle ID.

Return value

array All entities in the entity bundle.

Overrides TreeBuilderInterface::loadTree

File

src/Tree/EntityTreeBuilder.php, line 45

Class

EntityTreeBuilder
Provides a class for building a tree from general entity.

Namespace

Drupal\entity_reference_tree\Tree

Code

public function loadTree(string $entityType, string $bundleID, string $langCode = NULL, int $parent = 0, int $max_depth = NULL) {
  if ($this
    ->hasAccess()) {
    if ($bundleID === '*') {

      // Load all entities regardless bundles.
      $entities = \Drupal::entityTypeManager()
        ->getStorage($entityType)
        ->loadMultiple();
      $hasBundle = FALSE;
    }
    else {
      $hasBundle = TRUE;
      $entityStorage = \Drupal::entityTypeManager()
        ->getStorage($entityType);

      // Build the tree node for the bundle.
      $tree = [
        (object) [
          'id' => $bundleID,
          // Required.
          'parent' => '#',
          // Node text.
          'text' => $bundleID,
        ],
      ];

      // Entity query properties.
      $properties = [
        // Bundle key field.
        $entityStorage
          ->getEntityType()
          ->getKey('bundle') => $bundleID,
      ];

      // Load all entities matched the conditions.
      $entities = $entityStorage
        ->loadByProperties($properties);
    }

    // Build the tree.
    foreach ($entities as $entity) {
      $tree[] = (object) [
        'id' => $entity
          ->id(),
        // Required.
        'parent' => $hasBundle ? $entity
          ->bundle() : '#',
        // Node text.
        'text' => $entity
          ->label(),
      ];
    }
    return $tree;
  }

  // The user is not allowed to access taxonomy overviews.
  return NULL;
}