EntityReferenceTreeController.php in Entity Reference Tree Widget 8
File
src/Controller/EntityReferenceTreeController.php
View source
<?php
namespace Drupal\entity_reference_tree\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
class EntityReferenceTreeController extends ControllerBase {
protected $formBuilder;
protected $csrfToken;
public function __construct(FormBuilder $formBuilder, CsrfTokenGenerator $csrfToken) {
$this->formBuilder = $formBuilder;
$this->csrfToken = $csrfToken;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('form_builder'), $container
->get('csrf_token'));
}
public function openSearchForm(Request $request, string $field_edit_id, string $bundle, string $entity_type, string $theme, int $dots) {
$response = new AjaxResponse();
$modal_form = $this->formBuilder
->getForm('Drupal\\entity_reference_tree\\Form\\SearchForm', $field_edit_id, $bundle, $entity_type, $theme, $dots);
$response
->addCommand(new OpenModalDialogCommand($this
->t(ucfirst(str_replace('_', ' ', $entity_type)) . ' tree'), $modal_form, [
'width' => '800',
]));
return $response;
}
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!'));
}
if (\Drupal::hasService('entity_reference_' . $entity_type . '_tree_builder')) {
$treeBuilder = \Drupal::service('entity_reference_' . $entity_type . '_tree_builder');
}
else {
$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) {
$entityNodeAry[] = $treeBuilder
->createTreeNode($entity);
}
}
return new JsonResponse($entityNodeAry);
}
}