View source
<?php
namespace Drupal\term_reference_fancytree\Element;
use Drupal\Core\Entity\Query\QueryException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Component\Utility\Html;
use Drupal\taxonomy\Entity\Term;
class TermReferenceFancytree extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#process' => [
[
$class,
'processTree',
],
],
'#theme_wrappers' => [
'form_element',
],
];
}
public static function processTree(&$element, FormStateInterface $form_state, &$complete_form) {
if (!empty($element['#vocabulary'])) {
if ($form_state
->isProcessingInput() && !$form_state
->isRebuilding() && $form_state
->getValue($element['#parents'])) {
$ancestors = TermReferenceFancytree::getSelectedAncestors($form_state
->getValue($element['#parents']), TRUE);
}
else {
$ancestors = TermReferenceFancytree::getSelectedAncestors($element['#default_value'], FALSE);
}
$list = TermReferenceFancytree::getTopLevelNodes($element, $ancestors, $form_state);
$element['#attached']['library'][] = 'term_reference_fancytree/tree';
$element['#attached']['drupalSettings']['term_reference_fancytree'][$element['#id']]['tree'][] = [
'id' => $element['#id'],
'name' => $element['#name'],
'source' => $list,
'select_all' => $element['#select_all'],
'select_children' => $element['#select_children'],
];
if ($element['#select_all']) {
$element['#markup'] = '<a href="#" class="selectAll">Select all</a>';
}
$element['tree'] = [];
$element['tree']['#prefix'] = '<div id="' . $element['#id'] . '">';
$element['tree']['#suffix'] = '</div>';
}
return $element;
}
public static function getSelectedAncestors(array $values, $processing_input) {
$all_ancestors = [];
foreach ($values as $value) {
if (isset($value['target_id'])) {
if (!$processing_input) {
$value = $value['target_id'];
}
}
$term_ancestors = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadAllParents($value);
foreach ($term_ancestors as $ancestor) {
$all_ancestors[$ancestor
->id()] = $ancestor;
}
}
return $all_ancestors;
}
public static function getTopLevelNodes(array $element, array $ancestors, FormStateInterface $form_state) {
if (count($element['#vocabulary']) > 1) {
return TermReferenceFancytree::getVocabularyNamesJsonArray($element, $form_state, $ancestors);
}
else {
$taxonomy_vocabulary = \Drupal::entityTypeManager()
->getStorage('taxonomy_vocabulary')
->load(reset($element['#vocabulary'])
->id());
$terms = TermReferenceFancytree::loadTerms($taxonomy_vocabulary, 0);
return TermReferenceFancytree::getNestedListJsonArray($terms, $element, $ancestors, $form_state);
}
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$selected_terms = [];
if (is_array($input) && !empty($input)) {
foreach ($input as $tid) {
$term = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->load($tid);
if ($term) {
$selected_terms[] = $tid;
}
}
}
return $selected_terms;
}
public static function loadTerms($vocabulary, $parent = 0) {
try {
$query = \Drupal::entityQuery('taxonomy_term')
->condition('vid', $vocabulary
->id())
->condition('parent', $parent)
->sort('weight')
->sort('name');
$tids = $query
->execute();
$terms = TermReferenceFancytree::getTermStorage()
->loadMultiple($tids);
$language = \Drupal::languageManager()
->getCurrentLanguage()
->getId();
foreach ($terms as $tid => $term) {
if ($term
->hasTranslation($language)) {
$terms[$tid] = $term
->getTranslation($language);
}
}
return $terms;
} catch (QueryException $e) {
}
$database = \Drupal::database();
$query = $database
->select('taxonomy_term_data', 'td');
$query
->fields('td', [
'tid',
]);
$query
->condition('td.vid', $vocabulary
->id());
$query
->join('taxonomy_term_hierarchy', 'th', 'td.tid = th.tid AND th.parent = :parent', [
':parent' => $parent,
]);
$query
->join('taxonomy_term_field_data', 'tfd', 'td.tid = tfd.tid');
$query
->orderBy('tfd.weight');
$query
->orderBy('tfd.name');
$result = $query
->execute();
$tids = [];
foreach ($result as $record) {
$tids[] = $record->tid;
}
return \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadMultiple($tids);
}
public static function getNestedList($tree = [], $max_depth = NULL, $parent = 0, $parents_index = [], $depth = 0) {
foreach ($tree as $term) {
foreach ($term->parents as $term_parent) {
if ($term_parent == $parent) {
$return[$term
->id()] = $term;
}
else {
$parents_index[$term_parent][$term
->id()] = $term;
}
}
}
foreach ($return as &$term) {
if (isset($parents_index[$term
->id()]) && (is_null($max_depth) || $depth < $max_depth)) {
$term->children = TermReferenceFancytree::getNestedList($parents_index[$term
->id()], $max_depth, $term
->id(), $parents_index, $depth + 1);
}
}
return $return;
}
public static function getNestedListJsonArray($terms, $element, $ancestors = NULL, $form_state = NULL) {
$items = [];
if (!empty($terms)) {
foreach ($terms as $term) {
$item = [
'title' => Html::escape($term
->getName()),
'key' => $term
->id(),
];
if ($form_state && in_array($term
->id(), $form_state
->getValue($element['#parents']))) {
$item['selected'] = TRUE;
}
elseif (isset($element['#default_value']) && is_numeric(array_search($term
->id(), array_column($element['#default_value'], 'target_id')))) {
$item['selected'] = TRUE;
}
if (isset($ancestors[$term
->id()])) {
$item['extraClasses'] = "activeTrail";
$children = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadChildren($term
->id());
$child_items = self::getNestedListJsonArray($children, $element, $ancestors, $form_state);
if ($child_items) {
$item['children'] = $child_items;
}
}
elseif (isset($term->children) || TermReferenceFancytree::getChildCount($term
->id()) >= 1) {
if (isset($term->children)) {
$item['children'] = TermReferenceFancytree::getNestedListJsonArray($term->children, $element, $form_state);
}
else {
$item['lazy'] = TRUE;
}
}
$items[] = $item;
}
}
return $items;
}
public static function getVocabularyNamesJsonArray($element, $form_state, $ancestors = NULL) {
$items = [];
$vocabularies = $element['#vocabulary'];
if (!empty($vocabularies)) {
foreach ($vocabularies as $vocabulary) {
$item = [
'title' => Html::escape($vocabulary
->get('name')),
'key' => $vocabulary
->id(),
'vocab' => TRUE,
'unselectable' => TRUE,
'folder' => TRUE,
];
$terms = TermReferenceFancytree::loadTerms($vocabulary, 0);
$item['lazy'] = FALSE;
foreach ($terms as $term) {
if (isset($ancestors[$term
->id()])) {
$item['lazy'] = FALSE;
break;
}
else {
$item['lazy'] = TRUE;
}
}
if (!$item['lazy']) {
$item['extraClasses'] = 'activeTrail';
$item['children'] = TermReferenceFancytree::getNestedListJsonArray($terms, $element, $ancestors, $form_state);
}
$items[] = $item;
}
}
return $items;
}
public static function getChildCount($tid) {
static $tids = [];
if (!isset($tids[$tid])) {
$term = Term::load($tid);
$tids[$tid] = count(static::getTermStorage()
->loadTree($term
->bundle(), $tid, 1));
}
return $tids[$tid];
}
protected static function getTermStorage() {
return \Drupal::entityTypeManager()
->getStorage('taxonomy_term');
}
}