You are here

public function EntityReferenceTreeController::treeJson in Entity Reference Tree Widget 8

Same name and namespace in other branches
  1. 2.x src/Controller/EntityReferenceTreeController.php \Drupal\entity_reference_tree\Controller\EntityReferenceTreeController::treeJson()

Callback for JsTree json data.

1 string reference to 'EntityReferenceTreeController::treeJson'
entity_reference_tree.routing.yml in ./entity_reference_tree.routing.yml
entity_reference_tree.routing.yml

File

src/Controller/EntityReferenceTreeController.php, line 78

Class

EntityReferenceTreeController
EntityReferenceTreeController class.

Namespace

Drupal\entity_reference_tree\Controller

Code

public function treeJson(Request $request, string $entity_type, string $bundles) {
  $token = $request
    ->get('token');
  if (empty($token) || !$this->csrfToken
    ->validate($token, $bundles)) {
    return new Response($this
      ->t('Access denied!'));
  }

  // Instance a entity tree builder for this entity type if it exists.
  if (\Drupal::hasService('entity_reference_' . $entity_type . '_tree_builder')) {
    $treeBuilder = \Drupal::service('entity_reference_' . $entity_type . '_tree_builder');
  }
  else {

    // Todo: A basic entity tree builder.
    $treeBuilder = \Drupal::service('entity_reference_entity_tree_builder');
  }
  $bundlesAry = explode(',', $bundles);
  $entityTrees = [];
  $entityNodeAry = [];
  foreach ($bundlesAry as $bundle_id) {
    $tree = $treeBuilder
      ->loadTree($entity_type, $bundle_id);
    if (!empty($tree)) {
      $entityTrees[] = $tree;
    }
  }
  foreach ($entityTrees as $tree) {
    foreach ($tree as $entity) {

      // Create tree node for each entity.
      // Store them into an array passed to JS.
      // An array in JavaScript is indexed list.
      // JavaScript's array indices are always sequential
      // and start from 0.
      $entityNodeAry[] = $treeBuilder
        ->createTreeNode($entity);
    }
  }
  return new JsonResponse($entityNodeAry);
}