ShsController.php in Simple hierarchical select 8
File
src/Controller/ShsController.php
View source
<?php
namespace Drupal\shs\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\shs\Cache\ShsCacheableJsonResponse;
use Drupal\shs\Cache\ShsTermCacheDependency;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ShsController extends ControllerBase {
protected $container;
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public static function create(ContainerInterface $container) {
return new static($container);
}
public function getTermData($identifier, $bundle, $entity_id = 0) {
$context = [
'identifier' => $identifier,
'bundle' => $bundle,
'parent' => $entity_id,
];
$response = new ShsCacheableJsonResponse($context);
$cache_tags = [];
$result = [];
$langcode_current = $this
->languageManager()
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
$storage = $this
->entityTypeManager()
->getStorage('taxonomy_term');
$translation_enabled = FALSE;
if ($this
->moduleHandler()
->moduleExists('content_translation')) {
$translation_manager = $this->container
->get('content_translation.manager');
$translation_enabled = $translation_manager
->isEnabled('taxonomy_term', $bundle);
}
$terms = $storage
->loadTree($bundle, $entity_id, 1, $translation_enabled);
foreach ($terms as $term) {
$langcode = $langcode_current;
if ($translation_enabled && $term
->hasTranslation($langcode)) {
$term = $term
->getTranslation($langcode);
}
else {
$langcode = $term->default_langcode;
}
$tid = $translation_enabled ? $term
->id() : $term->tid;
$result[] = (object) [
'tid' => $tid,
'name' => $translation_enabled ? $term
->getName() : $term->name,
'description__value' => $translation_enabled ? $term
->getDescription() : $term->description__value,
'langcode' => $langcode,
'hasChildren' => shs_term_has_children($tid),
];
$cache_tags[] = sprintf('taxonomy_term:%d', $tid);
}
$response
->addCacheableDependency(new ShsTermCacheDependency($cache_tags));
$response
->setData($result, TRUE);
return $response;
}
}