term_reference_tree.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. use \Drupal\Core\Render\Element;
  3. /**
  4. * Implements hook_theme().
  5. */
  6. function term_reference_tree_theme() {
  7. return [
  8. 'checkbox_tree' => [
  9. 'render element' => 'element',
  10. 'function' => 'theme_checkbox_tree',
  11. ],
  12. 'checkbox_tree_level' => [
  13. 'render element' => 'element',
  14. 'function' => 'theme_checkbox_tree_level',
  15. ],
  16. 'checkbox_tree_item' => [
  17. 'render element' => 'element',
  18. 'function' => 'theme_checkbox_tree_item',
  19. ],
  20. 'checkbox_tree_label' => [
  21. 'render element' => 'element',
  22. 'function' => 'theme_checkbox_tree_label',
  23. ],
  24. 'term_tree_list' => [
  25. 'render element' => 'element',
  26. 'function' => 'theme_term_tree_list',
  27. ],
  28. ];
  29. }
  30. /**
  31. * Returns HTML for a checkbox_tree form element.
  32. */
  33. function theme_checkbox_tree($variables) {
  34. $element = $variables['element'];
  35. $element['#children'] = drupal_render_children($element);
  36. $attributes = isset($element['#attributes']) ? $element['#attributes'] : [];
  37. if (isset($element['#id'])) {
  38. $attributes['id'] = $element['#id'];
  39. }
  40. $attributes['class'][] = 'term-reference-tree';
  41. if (!empty($element['#required'])) {
  42. $attributes['class'][] = 'required';
  43. }
  44. if (array_key_exists('#start_minimized', $element) && $element['#start_minimized']) {
  45. $attributes['class'][] = 'term-reference-tree-collapsed';
  46. }
  47. if (array_key_exists('#track_list', $element) && $element['#track_list']) {
  48. $attributes['class'][] = 'term-reference-tree-track-list-shown';
  49. }
  50. if (!empty($variables['element']['#select_parents'])) {
  51. $attributes['class'][] = 'term-reference-tree-select-parents';
  52. }
  53. if ($variables['element']['#cascading_selection'] != \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_NONE) {
  54. $attributes['class'][] = 'term-reference-tree-cascading-selection';
  55. }
  56. if ($variables['element']['#cascading_selection'] == \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_SELECT) {
  57. $attributes['class'][] = 'term-reference-tree-cascading-selection-mode-select';
  58. }
  59. else {
  60. if ($variables['element']['#cascading_selection'] == \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_DESELECT) {
  61. $attributes['class'][] = 'term-reference-tree-cascading-selection-mode-deselect';
  62. }
  63. }
  64. if (!empty($element['#attributes']['class'])) {
  65. $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  66. }
  67. return
  68. '<div' . new \Drupal\Core\Template\Attribute($attributes) . '>'
  69. . (!empty($element['#children']) ? $element['#children'] : '')
  70. . '</div>';
  71. }
  72. /**
  73. * This function prints a list item with a checkbox and an unordered list
  74. * of all the elements inside it.
  75. */
  76. function theme_checkbox_tree_level($variables) {
  77. $element = $variables['element'];
  78. $sm = '';
  79. if (array_key_exists('#level_start_minimized', $element) && $element['#level_start_minimized']) {
  80. $sm = ' style="display: none;"';
  81. }
  82. $output = '<ul class="term-reference-tree-level "' . $sm . '>';
  83. $children = Element::children($element);
  84. foreach ($children as $child) {
  85. $output .= '<li>';
  86. $output .= \Drupal::service('renderer')->render($element[$child]);
  87. $output .= '</li>';
  88. }
  89. $output .= '</ul>';
  90. return $output;
  91. }
  92. /**
  93. * This function prints a single item in the tree, followed by that item's
  94. * children (which may be another checkbox_tree_level).
  95. */
  96. function theme_checkbox_tree_item($variables) {
  97. $element = $variables['element'];
  98. $children = Element::children($element);
  99. $output = '';
  100. $sm = $element['#level_start_minimized'] ? ' term-reference-tree-collapsed' : '';
  101. if (is_array($children) && count($children) > 1) {
  102. $output .= '<div class="term-reference-tree-button' . $sm . '"></div>';
  103. }
  104. elseif (!$element['#leaves_only']) {
  105. $output .= '<div class="no-term-reference-tree-button"></div>';
  106. }
  107. foreach ($children as $child) {
  108. $output .= drupal_render($element[$child]);
  109. }
  110. return $output;
  111. }
  112. /**
  113. * This function prints a label that cannot be selected.
  114. */
  115. function theme_checkbox_tree_label($variables) {
  116. $element = $variables['element'];
  117. $output = '<div class="parent-term">' . $element['#value'] . '</div>';
  118. return $output;
  119. }
  120. /**
  121. * This function returns a taxonomy term hierarchy in a nested array.
  122. *
  123. * @param $tid
  124. * The ID of the root term.
  125. * @param $vid
  126. * The vocabulary ID to restrict the child search.
  127. *
  128. * @return
  129. * A nested array of the term's child objects.
  130. */
  131. function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter, $label, $default = array()) {
  132. $terms = _term_reference_tree_get_children($tid, $vid);
  133. $result = [];
  134. if ($filter != '') {
  135. foreach ($allowed as $k => $v) {
  136. if (array_key_exists($k, $terms)) {
  137. $term =& $terms[$k];
  138. $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
  139. if (is_array($children)) {
  140. $term->children = $children;
  141. $term->children_selected = _term_reference_tree_children_selected($term, $default);
  142. }
  143. else {
  144. $term->children_selected = FALSE;
  145. }
  146. $term->TEST = $label;
  147. array_push($result, $term);
  148. }
  149. }
  150. }
  151. else {
  152. foreach ($terms as &$term) {
  153. if ($filter == '' || array_key_exists($term->tid, $allowed)) {
  154. $children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
  155. if (is_array($children)) {
  156. $term->children = $children;
  157. $term->children_selected = _term_reference_tree_children_selected($term, $default);
  158. }
  159. else {
  160. $term->children_selected = FALSE;
  161. }
  162. $term->TEST = $label;
  163. array_push($result, $term);
  164. }
  165. }
  166. }
  167. return $result;
  168. }
  169. /**
  170. * This function is like taxonomy_get_children, except it doesn't load the
  171. * entire term.
  172. *
  173. * @param int $tid
  174. * The ID of the term whose children you want to get.
  175. * @param int $vid
  176. * The vocabulary ID.
  177. *
  178. * @return array
  179. * Taxonomy terms, each in the form ['tid' => $tid, 'name' => $name].
  180. */
  181. function _term_reference_tree_get_children($tid, $vid) {
  182. // DO NOT LOAD TAXONOMY TERMS HERE.
  183. // Taxonomy terms take a lot of time and memory to load, and this can be
  184. // very bad on large vocabularies. Instead, we load the term as necessary
  185. // in cases where it's needed (such as using tokens or when the locale
  186. // module is enabled).
  187. $table = 'taxonomy_term_field_data';
  188. $alias = 't';
  189. $query = \Drupal::database()
  190. ->select($table, $alias);
  191. $query->join('taxonomy_term__parent', 'p', 't.tid = p.entity_id');
  192. $query->fields('t', ['tid', 'name']);
  193. $query->addField('t', 'vid', 'vocabulary_machine_name');
  194. $query
  195. ->condition('t.vid', $vid)
  196. ->condition('p.parent_target_id', $tid)
  197. ->addTag('term_access')
  198. ->addTag('translatable')
  199. ->orderBy('t.weight')
  200. ->orderBy('t.name');
  201. $result = $query->execute();
  202. $terms = [];
  203. while ($term = $result->fetchObject()) {
  204. $terms[$term->tid] = $term;
  205. }
  206. return $terms;
  207. }
  208. function _term_reference_tree_children_selected($terms, $default) {
  209. foreach ($terms->children as $term) {
  210. if (isset($default[$term->tid]) || $term->children_selected) {
  211. return TRUE;
  212. }
  213. }
  214. return FALSE;
  215. }
  216. /**
  217. * Recursively go through the option tree and return a flat array of options.
  218. */
  219. function _term_reference_tree_flatten($element, &$form_state) {
  220. $output = array();
  221. $children = \Drupal\Core\Render\Element::children($element);
  222. foreach ($children as $c) {
  223. $child = $element[$c];
  224. if (array_key_exists('#type', $child) && ($child['#type'] == 'radio' || $child['#type'] == 'checkbox')) {
  225. $output[] = $child;
  226. }
  227. else {
  228. $output = array_merge($output, _term_reference_tree_flatten($child, $form_state));
  229. }
  230. }
  231. return $output;
  232. }
  233. /**
  234. * Return an array of options.
  235. *
  236. * This function converts a list of taxonomy terms to a key/value list of
  237. * options.
  238. */
  239. function _term_reference_tree_get_options(&$terms, &$allowed, $filter) {
  240. $options = array();
  241. if (is_array($terms) && count($terms) > 0) {
  242. foreach ($terms as $term) {
  243. if (!$filter || (is_array($allowed) && $allowed[$term->tid])) {
  244. $options[$term->tid] = $term->name;
  245. $options += _term_reference_tree_get_options($term->children, $allowed, $filter);
  246. }
  247. }
  248. }
  249. return $options;
  250. }
  251. /**
  252. * Builds a level in the term reference tree widget.
  253. *
  254. * This function returns an element that has a number of checkbox_tree_item
  255. * elements as children. It is meant to be called recursively when the widget
  256. * is built.
  257. */
  258. function _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $parent_tids, $depth) {
  259. $start_minimized = TRUE;
  260. $leaves_only = FALSE;
  261. $container = array(
  262. '#type' => 'checkbox_tree_level',
  263. '#max_choices' => $max_choices,
  264. '#leaves_only' => $leaves_only,
  265. '#start_minimized' => $start_minimized,
  266. '#depth' => $depth,
  267. );
  268. $container['#level_start_minimized'] = $depth > 1 && $element['#start_minimized'] && !($term->children_selected);
  269. foreach ($term->children as $child) {
  270. $container[$child->tid] = _term_reference_tree_build_item($element, $child, $form_state, $value, $max_choices, $parent_tids, $container, $depth);
  271. }
  272. return $container;
  273. }
  274. /**
  275. * Builds a single item in the term reference tree widget.
  276. *
  277. * This function returns an element with a checkbox for a single taxonomy term.
  278. * If that term has children, it appends checkbox_tree_level element that
  279. * contains the children. It is meant to be called recursively when the widget
  280. * is built.
  281. */
  282. function _term_reference_tree_build_item($element, $term, $form_state, $value, $max_choices, $parent_tids, $parent, $depth) {
  283. $leaves_only = FALSE;
  284. $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  285. $t = NULL;
  286. if (\Drupal::moduleHandler()->moduleExists('locale') && !empty($term->tid)) {
  287. $t = \Drupal::entityManager()
  288. ->getStorage('taxonomy_term')
  289. ->load($term->tid);
  290. if ($t && $t->hasTranslation($langcode)) {
  291. $term_name = $t->getTranslation($langcode)->label();
  292. }
  293. }
  294. if (empty($term_name)) {
  295. $term_name = $term->name;
  296. }
  297. $container = array(
  298. '#type' => 'checkbox_tree_item',
  299. '#max_choices' => $max_choices,
  300. '#leaves_only' => $leaves_only,
  301. '#term_name' => $term_name,
  302. '#level_start_minimized' => FALSE,
  303. '#select_parents' => $element['#select_parents'],
  304. '#depth' => $depth,
  305. );
  306. if (!$element['#leaves_only'] || count($term->children) == 0) {
  307. $e = array(
  308. '#type' => ($max_choices == 1) ? 'radio' : 'checkbox',
  309. '#title' => $term_name,
  310. '#on_value' => $term->tid,
  311. '#off_value' => 0,
  312. '#return_value' => $term->tid,
  313. '#parent_values' => $parent_tids,
  314. '#default_value' => isset($value[$term->tid]) ? $term->tid : NULL,
  315. '#attributes' => isset($element['#attributes']) ? $element['#attributes'] : NULL,
  316. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  317. );
  318. if ($e['#type'] == 'radio') {
  319. $parents_for_id = array_merge($element['#parents'], array($term->tid));
  320. $e['#id'] = \Drupal\Component\Utility\Html::getId('edit-' . implode('-', $parents_for_id));
  321. $e['#parents'] = $element['#parents'];
  322. }
  323. }
  324. else {
  325. $e = array(
  326. '#type' => 'checkbox_tree_label',
  327. '#value' => $term_name,
  328. );
  329. }
  330. $container[$term->tid] = $e;
  331. if (($depth + 1 <= $element['#max_depth'] || !$element['#max_depth']) && property_exists($term, 'children') && count($term->children) > 0) {
  332. $parents = $parent_tids;
  333. $parents[] = $term->tid;
  334. $container[$term->tid . '-children'] = _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $parents, $depth + 1);
  335. $container['#level_start_minimized'] = $container[$term->tid . '-children']['#level_start_minimized'];
  336. }
  337. return $container;
  338. }
  339. /**
  340. * Themes the term tree display (as opposed to the select widget).
  341. */
  342. function theme_term_tree_list($variables) {
  343. $element = &$variables['element'];
  344. $data = &$element['#data'];
  345. $tree = [];
  346. // For each selected term.
  347. foreach ($data as $item) {
  348. // Loop if the term ID is not zero.
  349. $values = [];
  350. $tid = $item['target_id'];
  351. $original_tid = $tid;
  352. while ($tid != 0) {
  353. // Unshift the term onto an array.
  354. array_unshift($values, $tid);
  355. // Repeat with parent term.
  356. $tid = _term_reference_tree_get_parent($tid);
  357. }
  358. $current = &$tree;
  359. // For each term in the above array.
  360. foreach ($values as $tid) {
  361. // current[children][term_id] = new array.
  362. if (!isset($current['children'][$tid])) {
  363. $current['children'][$tid] = ['selected' => FALSE];
  364. }
  365. // If this is the last value in the array,
  366. // tree[children][term_id][selected] = true.
  367. if ($tid == $original_tid) {
  368. $current['children'][$tid]['selected'] = TRUE;
  369. }
  370. $current['children'][$tid]['tid'] = $tid;
  371. $current = &$current['children'][$tid];
  372. }
  373. }
  374. $output = '<div class="term-tree-list">';
  375. $output .= _term_reference_tree_output_list_level($element, $tree);
  376. $output .= '</div>';
  377. return $output;
  378. }
  379. /**
  380. * Helper function to get the parent of tid.
  381. *
  382. * @param int $tid
  383. * The term id.
  384. *
  385. * @return int
  386. * Parent term id or 0.
  387. */
  388. function _term_reference_tree_get_parent($tid) {
  389. $query = "SELECT p.parent_target_id FROM {taxonomy_term__parent} p WHERE p.entity_id = :tid";
  390. $from = 0;
  391. $count = 1;
  392. $args = [':tid' => $tid];
  393. $database = \Drupal::database();
  394. $result = $database->queryRange($query, $from, $count, $args);
  395. $parent_tid = 0;
  396. foreach ($result as $term) {
  397. $parent_tid = $term->parent_target_id;
  398. }
  399. return $parent_tid;
  400. }
  401. /**
  402. * Helper function to output a single level of the term reference tree display.
  403. */
  404. function _term_reference_tree_output_list_level(&$element, &$tree) {
  405. $output = '';
  406. $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  407. if (isset($tree['children']) && is_array($tree['children']) && count($tree['children']) > 0) {
  408. $output = '<ul class="term">';
  409. foreach ($tree['children'] as &$item) {
  410. if (isset($item['tid'])) {
  411. $term = \Drupal\taxonomy\Entity\Term::load($item['tid']);
  412. $url = $term->toUrl();
  413. $uri['options']['html'] = TRUE;
  414. $class = $item['selected'] ? 'selected' : 'unselected';
  415. $output .= '<li class="' . $class . '">';
  416. $t = NULL;
  417. $term_name = '';
  418. if (\Drupal::moduleHandler()
  419. ->moduleExists('locale') && !empty($term->tid)) {
  420. $t = $term;
  421. if ($t && $t->hasTranslation($langcode)) {
  422. $term_name = $t->getTranslation($langcode)->label();
  423. }
  424. }
  425. if (empty($term_name)) {
  426. $term_name = $term->label();
  427. }
  428. $output .= \Drupal::service('link_generator')
  429. ->generate($term_name, $url);
  430. if (isset($item['children'])) {
  431. $output .= _term_reference_tree_output_list_level($element, $item);
  432. }
  433. $output .= '</li>';
  434. }
  435. }
  436. $output .= '</ul>';
  437. }
  438. return $output;
  439. }