term_reference_tree.widget.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. <?php
  2. /**
  3. * Implements hook_field_widget_info().
  4. */
  5. function term_reference_tree_field_widget_info() {
  6. return array(
  7. 'term_reference_tree' => array (
  8. 'label' => 'Term reference tree',
  9. 'field types' => array('taxonomy_term_reference'),
  10. 'behaviors' => array(
  11. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  12. 'default value' => FIELD_BEHAVIOR_DEFAULT,
  13. ),
  14. 'settings' => array(
  15. 'start_minimized' => 0,
  16. 'leaves_only' => 0,
  17. 'filter_view' => '',
  18. 'select_parents' => 0,
  19. 'cascading_selection' => 0,
  20. 'track_list' => 0,
  21. 'track_list_order' => 0,
  22. 'token_display' => '',
  23. 'parent_term_id' => '',
  24. 'max_depth' => '',
  25. 'starting_depth' => 1,
  26. ),
  27. ),
  28. );
  29. }
  30. /**
  31. * Themes the term tree display (as opposed to the select widget).
  32. */
  33. function theme_term_tree_list($variables) {
  34. $element =& $variables['element'];
  35. $data =& $element['#data'];
  36. $tree = array();
  37. # For each selected term:
  38. foreach($data as $item) {
  39. # Loop if the term ID is not zero:
  40. $values = array();
  41. $tid = $item['tid'];
  42. $original_tid = $tid;
  43. while($tid != 0) {
  44. # Unshift the term onto an array
  45. array_unshift($values, $tid);
  46. # Repeat with parent term
  47. $tid = _term_reference_tree_get_parent($tid);
  48. }
  49. $current =& $tree;
  50. # For each term in the above array:
  51. foreach($values as $tid) {
  52. # current[children][term_id] = new array
  53. if (!isset($current['children'][$tid])) {
  54. $current['children'][$tid] = array('selected' => FALSE);
  55. }
  56. # If this is the last value in the array, tree[children][term_id][selected] = true
  57. if ($tid == $original_tid) {
  58. $current['children'][$tid]['selected'] = TRUE;
  59. }
  60. $current['children'][$tid]['tid'] = $tid;
  61. $current =& $current['children'][$tid];
  62. }
  63. }
  64. return _term_reference_tree_output_list_level($element, $tree);
  65. }
  66. /**
  67. * Implements hook_field_widget_settings_form().
  68. */
  69. function term_reference_tree_field_widget_settings_form($field, $instance) {
  70. $widget = $instance['widget'];
  71. $settings = $widget['settings'];
  72. $form = array();
  73. if ($widget['type'] == 'term_reference_tree') {
  74. $form['start_minimized'] = array(
  75. '#type' => 'checkbox',
  76. '#title' => t('Start minimized'),
  77. '#description' => t('Make the tree appear minimized on the form by default'),
  78. '#default_value' => $settings['start_minimized'],
  79. '#return_value' => 1,
  80. );
  81. $form['leaves_only'] = array(
  82. '#type' => 'checkbox',
  83. '#title' => t('Leaves only'),
  84. '#description' => t("Don't allow the user to select items that have children"),
  85. '#default_value' => $settings['leaves_only'],
  86. '#return_value' => 1,
  87. );
  88. $form['select_parents'] = array(
  89. '#type' => 'checkbox',
  90. '#title' => t('Select parents automatically'),
  91. '#description' => t("When turned on, this option causes the widget to automatically select the ancestors of all selected items. In Leaves Only mode, the parents will be added invisibly to the selected value. <em>This option is only valid if an unlimited number of values can be selected.</em>"),
  92. '#default_value' => $settings['select_parents'],
  93. '#element_validate' => array('_term_reference_tree_select_parents_validate'),
  94. '#return_value' => 1,
  95. );
  96. $form['cascading_selection'] = array(
  97. '#type' => 'checkbox',
  98. '#title' => t('Cascading selection'),
  99. '#description' => t('On parent selection, automatically select children if none were selected. Some may then be manually unselected. In the same way, on parent unselection, unselect children if all were selected. <em>This option is only valid if an unlimited number of values can be selected.</em>'),
  100. '#default_value' => $settings['cascading_selection'],
  101. '#element_validate' => array('_term_reference_tree_cascading_selection_validate'),
  102. '#return_value' => 1,
  103. );
  104. if (module_exists('views')) {
  105. $views = views_get_all_views();
  106. $options = array('' => 'none');
  107. foreach($views as $name => $view) {
  108. if ($view->base_table == 'taxonomy_term_data') {
  109. foreach($view->display as $display) {
  110. $options["$name:{$display->id}"] = "{$view->human_name}: {$display->display_title}";
  111. }
  112. }
  113. }
  114. $form['filter_view'] = array(
  115. '#type' => 'select',
  116. '#title' => 'Filter by view',
  117. '#description' => t("Filter the available options based on whether they appear in the selected view."),
  118. '#default_value' => $settings['filter_view'],
  119. '#options' => $options,
  120. );
  121. }
  122. else {
  123. $form['filter_view'] = array(
  124. '#type' => 'hidden',
  125. '#value' => $settings['filter_view'],
  126. );
  127. }
  128. if (module_exists('token')) {
  129. $form['token_display'] = array(
  130. '#type' => 'textarea',
  131. '#title' => 'Custom Term Label',
  132. '#description' => t("Use tokens to change the term labels for the checkboxes and/or radio buttons. Leave this field blank to use the term name."),
  133. '#default_value' => $settings['token_display'],
  134. );
  135. $form['tokens_list'] = array(
  136. '#theme' => 'token_tree',
  137. '#token_types' => array('term'),
  138. );
  139. }
  140. else {
  141. $form['token_display'] = array(
  142. '#type' => 'hidden',
  143. '#value' => $settings['token_display'],
  144. );
  145. }
  146. $form['track_list'] = array(
  147. '#type' => 'checkbox',
  148. '#title' => t('Track list'),
  149. '#description' => t(
  150. 'Track what the user has chosen in a list below the tree.
  151. Useful when the tree is large, with many levels.'),
  152. '#default_value' => $settings['track_list'],
  153. '#return_value' => 1,
  154. );
  155. $form['track_list_order'] = array(
  156. '#type' => 'checkbox',
  157. '#title' => t('Track list drag and drop order'),
  158. '#description' => t(
  159. 'Allow drag and drop selected terms ordering on tracklist.'),
  160. '#default_value' => $settings['track_list_order'],
  161. '#return_value' => 1,
  162. '#element_validate' => array('_term_reference_tree_track_list_order_validate'),
  163. );
  164. $form['max_depth'] = array(
  165. '#type' => 'textfield',
  166. '#title' => t('Maximum Depth'),
  167. '#description' => t("Only show items up to this many levels deep."),
  168. '#default_value' => $settings['max_depth'],
  169. '#size' => 2,
  170. '#return_value' => 1,
  171. );
  172. $form['starting_depth'] = array(
  173. '#type' => 'textfield',
  174. '#title' => t('Starting Depth'),
  175. '#description' => t("Only items equal and down this level will be selectable. First level is 1"),
  176. '#default_value' => $settings['starting_depth'],
  177. '#size' => 2,
  178. '#return_value' => 1,
  179. );
  180. $form['parent_term_id'] = array(
  181. '#type' => 'textfield',
  182. '#title' => t('Parent Term ID'),
  183. '#description' => t("Only show items underneath the taxonomy term with this ID number. Leave this field blank to not limit terms by parent."),
  184. '#default_value' => $settings['parent_term_id'],
  185. '#size' => 8,
  186. '#return_value' => 1,
  187. );
  188. }
  189. return $form;
  190. }
  191. /**
  192. * Helper function to output a single level of the term reference tree
  193. * display.
  194. */
  195. function _term_reference_tree_output_list_level(&$element, &$tree) {
  196. if (isset($tree['children']) && is_array($tree['children']) && count($tree['children'] > 0)) {
  197. $output = '<ul class="term">';
  198. $settings = $element['#display']['settings'];
  199. $tokens_selected = $settings['token_display_selected'];
  200. $tokens_unselected = ($settings['token_display_unselected'] != '') ? $settings['token_display_unselected'] : $tokens_selected;
  201. foreach($tree['children'] as &$item) {
  202. $term = taxonomy_term_load($item['tid']);
  203. $uri = taxonomy_term_uri($term);
  204. $class = $item['selected'] ? 'selected' : 'unselected';
  205. $output .= "<li class='$class'>";
  206. if ($tokens_selected != '' && module_exists('token')) {
  207. $replace = $item['selected'] ? $tokens_selected : $tokens_unselected;
  208. $output .= token_replace($replace, array('term' => $term), array('clear' => TRUE));
  209. }
  210. else {
  211. $output .= l(entity_label('taxonomy_term', $term), $uri['path'], array('html' => true));
  212. }
  213. if (isset($item['children'])) {
  214. $output .= _term_reference_tree_output_list_level($element, $item);
  215. }
  216. $output .= "</li>";
  217. }
  218. $output .= '</ul>';
  219. return $output;
  220. }
  221. }
  222. /**
  223. * Makes sure that cardinality is unlimited if auto-select parents is enabled.
  224. */
  225. function _term_reference_tree_select_parents_validate($element, &$form_state) {
  226. if ($form_state['values']['instance']['widget']['settings']['select_parents'] == 1 && $form_state['values']['field']['cardinality'] != -1) {
  227. // This is pretty wonky syntax for the field name in form_set_error, but it's
  228. // correct.
  229. form_set_error('field][cardinality', t('You must select an Unlimited number of values if Select Parents Automatically is enabled.'));
  230. }
  231. }
  232. /**
  233. * Makes sure that cardinality is unlimited if cascading selection is enabled.
  234. */
  235. function _term_reference_tree_cascading_selection_validate($element, &$form_state) {
  236. if ($form_state['values']['instance']['widget']['settings']['cascading_selection'] == 1 && $form_state['values']['field']['cardinality'] != -1) {
  237. // This is pretty wonky syntax for the field name in form_set_error, but it's
  238. // correct.
  239. form_set_error('field][cardinality', t('You must select an Unlimited number of values if Cascading selection is enabled.'));
  240. }
  241. }
  242. function _term_reference_tree_track_list_order_validate($element, &$form_state){
  243. if ($form_state['values']['instance']['widget']['settings']['track_list'] == 0 && $form_state['values']['instance']['widget']['settings']['track_list_order'] == 1) {
  244. // This is pretty wonky syntax for the field name in form_set_error, but it's
  245. // correct.
  246. form_set_error('field][track_list_order', t('You must enable Track List if Track List Order is enabled.'));
  247. }
  248. /*
  249. TODO check if number of values is diffrent from 1
  250. */
  251. }
  252. /**
  253. * Process the checkbox_tree widget.
  254. *
  255. * This function processes the checkbox_tree widget.
  256. *
  257. * @param $element
  258. * The element to be drawn.$element['#field_name']
  259. * @param $form_state
  260. * The form state.
  261. *
  262. * @return
  263. * The processed element.
  264. */
  265. function term_reference_tree_process_checkbox_tree($element, $form_state) {
  266. if (is_array($form_state)) {
  267. if (!empty($element['#max_choices']) && $element['#max_choices'] != '-1')
  268. drupal_add_js(array('term_reference_tree' => array('trees' => array($element['#id'] => array('max_choices'=>$element['#max_choices'])))), 'setting');
  269. $allowed = '';
  270. if ($element['#filter_view'] != '') {
  271. $allowed = _term_reference_tree_get_allowed_values($element['#filter_view']);
  272. }
  273. $value = !empty($element['#default_value']) ? $element['#default_value'] : array();
  274. if (empty($element['#options'])) {
  275. $element['#options_tree'] = _term_reference_tree_get_term_hierarchy($element['#parent_tid'], $element['#vocabulary'], $allowed, $element['#filter_view'], '', $value);
  276. $required = $element['#required'];
  277. if ($element['#max_choices'] == 1 && !$required) {
  278. array_unshift($element['#options_tree'], (object) array(
  279. 'tid' => '',
  280. 'name' => 'N/A',
  281. 'depth' => 0
  282. )
  283. );
  284. }
  285. $element['#options'] = _term_reference_tree_get_options($element['#options_tree'], $allowed, $element['#filter_view']);
  286. }
  287. $terms = !empty($element['#options_tree']) ? $element['#options_tree'] : array();
  288. $max_choices = !empty($element['#max_choices']) ? $element['#max_choices'] : 1;
  289. if (array_key_exists('#select_parents', $element) && $element['#select_parents']) {
  290. $element['#attributes']['class'][] = 'select-parents';
  291. }
  292. if ($max_choices != 1)
  293. $element['#tree'] = TRUE;
  294. $starting_depth = !empty($element['#starting_depth']) ? $element['#starting_depth'] : 0;
  295. $tree = new stdClass;
  296. $tree->children = $terms;
  297. $element[] = _term_reference_tree_build_level($element, $tree, $form_state, $value, $max_choices, $starting_depth, array(), 1);
  298. //Add a track list element?
  299. $track_list = !empty($element['#track_list']) && $element['#track_list'];
  300. if ( $track_list ) {
  301. $element[] = array(
  302. '#type' => 'checkbox_tree_track_list',
  303. '#max_choices' => $max_choices,
  304. '#track_list_order' => $element['#track_list_order'],
  305. );
  306. }
  307. }
  308. return $element;
  309. }
  310. /**
  311. * Returns HTML for a checkbox_tree form element.
  312. *
  313. * @param $variables
  314. * An associative array containing:
  315. * - element: An associative array containing the properties of the element.
  316. *
  317. * @ingroup themeable
  318. */
  319. function theme_checkbox_tree($variables) {
  320. $element = $variables['element'];
  321. $element['#children'] = drupal_render_children($element);
  322. $attributes = array();
  323. if (isset($element['#id'])) {
  324. $attributes['id'] = $element['#id'];
  325. }
  326. $attributes['class'][] = 'term-reference-tree';
  327. if (form_get_error($element)) {
  328. $attributes['class'][] = 'error';
  329. }
  330. if (!empty($element['#required'])) {
  331. $attributes['class'][] = 'required';
  332. }
  333. if (array_key_exists('#start_minimized', $element) && $element['#start_minimized']) {
  334. $attributes['class'][] = "term-reference-tree-collapsed";
  335. }
  336. if (array_key_exists('#cascading_selection', $element) && $element['#cascading_selection']) {
  337. $attributes['class'][] = "term-reference-tree-cascading-selection";
  338. }
  339. $add_track_list = FALSE;
  340. if (array_key_exists('#track_list', $element) && $element['#track_list']) {
  341. $attributes['class'][] = "term-reference-tree-track-list-shown";
  342. $add_track_list = TRUE;
  343. }
  344. if (!empty($element['#attributes']['class'])) {
  345. $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  346. }
  347. return
  348. '<div' . drupal_attributes($attributes) . '>'
  349. . (!empty($element['#children']) ? $element['#children'] : '')
  350. . '</div>';
  351. }
  352. /**
  353. * This function prints a list item with a checkbox and an unordered list
  354. * of all the elements inside it.
  355. */
  356. function theme_checkbox_tree_level($variables) {
  357. $element = $variables['element'];
  358. $sm = '';
  359. if (array_key_exists('#level_start_minimized', $element) && $element['#level_start_minimized']) {
  360. $collapsed =
  361. $sm = " style='display: none;'";
  362. }
  363. $max_choices = 0;
  364. if (array_key_exists('#max_choices', $element)) {
  365. $max_choices = $element['#max_choices'];
  366. }
  367. $output = "<ul class='term-reference-tree-level '$sm>";
  368. $children = element_children($element);
  369. foreach($children as $child) {
  370. $output .= "<li>";
  371. $output .= drupal_render($element[$child]);
  372. $output .= "</li>";
  373. }
  374. $output .= "</ul>";
  375. return $output;
  376. }
  377. /**
  378. * This function prints a single item in the tree, followed by that item's children
  379. * (which may be another checkbox_tree_level).
  380. */
  381. function theme_checkbox_tree_item($variables) {
  382. $element = $variables['element'];
  383. $children = element_children($element);
  384. $output = "";
  385. $sm = $element['#level_start_minimized'] ? ' term-reference-tree-collapsed' : '';
  386. if (is_array($children) && count($children) > 1) {
  387. $output .= "<div class='term-reference-tree-button$sm'></div>";
  388. }
  389. elseif (!$element['#leaves_only']) {
  390. $output .= "<div class='no-term-reference-tree-button'></div>";
  391. }
  392. foreach($children as $child) {
  393. $output .= drupal_render($element[$child]);
  394. }
  395. return $output;
  396. }
  397. /**
  398. * This function prints a label that cannot be selected.
  399. */
  400. function theme_checkbox_tree_label($variables) {
  401. // dsm($variables, 'variables');
  402. $element = $variables['element'];
  403. $output = "<div class='parent-term'>" . $element['#value'] . "</div>";
  404. return $output;
  405. }
  406. /**
  407. * Shows a list of items that have been checked.
  408. * The display happens on the client-side.
  409. * Use this function to theme the element's label,
  410. * and the "nothing selected" message.
  411. *
  412. * @param $variables Variables available for theming.
  413. */
  414. function theme_checkbox_tree_track_list($variables) {
  415. //Should the label be singular or plural? Depends on cardinality of term field.
  416. static $nothingselected;
  417. // dsm($variables, 'theme_checkbox_tree_track_list : $variables');
  418. if(!$nothingselected) {
  419. $nothingselected = t('[Nothing selected]');
  420. //Add the "Nothing selected" text. To style it, replace it with whatever you want.
  421. //Could do this with a file instead.
  422. drupal_add_js(
  423. 'var termReferenceTreeNothingSelectedText = "' . $nothingselected . '";',
  424. 'inline'
  425. );
  426. }
  427. $label = format_plural(
  428. $variables['element']['#max_choices'],
  429. 'Selected item (click the item to uncheck it)',
  430. 'Selected items (click an item to uncheck it)'
  431. );
  432. $order = $variables['element']['#track_list_order'] ? 'order-list' : '';
  433. $output =
  434. '<div class="term-reference-track-list-container">
  435. <div class="term-reference-track-list-label">' . $label . '</div>
  436. <ul class="term-reference-tree-track-list '.$order.'"><li class="term_ref_tree_nothing_message">'.$nothingselected.'</li></ul>
  437. </div>';
  438. return $output;
  439. }
  440. /**
  441. * Implements hook_widget_field_form().
  442. */
  443. function term_reference_tree_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  444. $settings = $instance['widget']['settings'];
  445. $voc = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
  446. $path = drupal_get_path('module', 'term_reference_tree');
  447. $value_key = key($field['columns']);
  448. $type = $instance['widget']['type'];
  449. $default_value = array();
  450. foreach($items as $item) {
  451. $key = $item[$value_key];
  452. if ($key === 0) {
  453. $default_value[$key] = '0';
  454. }
  455. else {
  456. $default_value[$key] = $key;
  457. }
  458. }
  459. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  460. $properties = array();
  461. if (!array_key_exists('#value', $element))
  462. $element['#value'] = array();
  463. // A switch statement, in case we ever add more widgets to this module.
  464. switch($instance['widget']['type']) {
  465. case 'term_reference_tree':
  466. $element['#attached']['js'] = array($path . '/term_reference_tree.js');
  467. $element['#attached']['css'] = array($path . '/term_reference_tree.css');
  468. $element['#type'] = 'checkbox_tree';
  469. $element['#default_value'] = $multiple ? $default_value : array(reset($default_value) => reset($default_value));
  470. $element['#max_choices'] = $field['cardinality'];
  471. $element['#max_depth'] = $settings['max_depth'];
  472. $element['#starting_depth'] = $settings['starting_depth'];
  473. $element['#start_minimized'] = $settings['start_minimized'];
  474. $element['#leaves_only'] = $settings['leaves_only'];
  475. $element['#filter_view'] = module_exists('views') ? $settings['filter_view'] : '';
  476. $element['#select_parents'] = $settings['select_parents'];
  477. $element['#cascading_selection'] = $settings['cascading_selection'];
  478. $element['#track_list'] = $settings['track_list'];
  479. $element['#track_list_order'] = $settings['track_list_order'];
  480. $element['#parent_tid'] = $settings['parent_term_id'] || $field['settings']['allowed_values'][0]['parent'];
  481. $element['#vocabulary'] = $voc->vid;
  482. $element['#token_display'] = module_exists('token') ? $settings['token_display'] : '';
  483. break;
  484. }
  485. $element += array(
  486. '#value_key' => $value_key,
  487. '#element_validate' => array('_term_reference_tree_widget_validate'),
  488. '#properties' => $properties,
  489. );
  490. if ($settings['track_list_order']) {
  491. drupal_add_library('system', 'ui.sortable');
  492. }
  493. return $element;
  494. }
  495. /**
  496. * Validates the term reference tree widgets.
  497. *
  498. * This function sets the value of the tree widgets into a form that Drupal
  499. * can understand, and also checks if the field is required and has been
  500. * left empty.
  501. *
  502. * @param $element
  503. * The element to be validated.
  504. * @param $form_state
  505. * The state of the form.
  506. *
  507. * @return
  508. * The validated element.
  509. */
  510. function _term_reference_tree_widget_validate(&$element, &$form_state) {
  511. // dsm($element, '$element');
  512. // dsm($form_state, '$form_state');
  513. # if the field was in the form
  514. if(isset($form_state['input'][$element['#field_name']])){
  515. $items = _term_reference_tree_flatten($element, $form_state);
  516. $value = array();
  517. if ($element['#max_choices'] != 1) {
  518. if(!$element['#track_list_order']){
  519. foreach($items as $child) {
  520. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  521. array_push($value, array( $element['#value_key'] => $child['#value']));
  522. // If the element is leaves only and select parents is on, then automatically
  523. // add all the parents of each selected value.
  524. if ($element['#select_parents'] && $element['#leaves_only']) {
  525. foreach($child['#parent_values'] as $parent_tid) {
  526. if (!in_array(array($element['#value_key'] => $parent_tid), $value)) {
  527. array_push($value, array($element['#value_key'] => $parent_tid));
  528. }
  529. }
  530. }
  531. }
  532. }
  533. }else{
  534. $selected_terms = array();
  535. $deltas = array();
  536. foreach($items as $child) {
  537. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  538. $selected_terms[] = array(
  539. "delta" => $form_state['input'][$child['#value'].'-weight'],
  540. "term" => array($element['#value_key'] => $child['#value']),
  541. );
  542. // If the element is leaves only and select parents is on, then automatically
  543. // add all the parents of each selected value.
  544. if ($element['#select_parents'] && $element['#leaves_only']) {
  545. foreach($child['#parent_values'] as $parent_tid) {
  546. if (!in_array(array($element['#value_key'] => $parent_tid), $selected_terms)) {
  547. $selected_terms[] = array(
  548. "delta" => $form_state['input'][$parent_tid.'-weight'],
  549. "term" => array($element['#value_key'] => $child['#value']),
  550. );
  551. }
  552. }
  553. }
  554. }
  555. }
  556. // dsm($deltas, '$deltas');
  557. // dsm($selected_terms, '$selected_terms before sort');
  558. // reorder items
  559. function delta_sort($a, $b){
  560. return $a['delta'] > $b['delta'];
  561. }
  562. usort($selected_terms, "delta_sort");
  563. // dsm($selected_terms, '$selected_terms after sort');
  564. // record in value
  565. foreach ($selected_terms as $selected_term) {
  566. $value[] = $selected_term['term'];
  567. }
  568. }
  569. }
  570. else {
  571. // If it's a tree of radio buttons, they all have the same value, so we can just
  572. // grab the value of the first one.
  573. if (count($items) > 0) {
  574. $child = reset($items);
  575. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  576. array_push($value, array($element['#value_key'] => $child['#value']));
  577. }
  578. }
  579. }
  580. if ($element['#required'] && empty($value)) {
  581. // The title is already check_plained so it's appropriate to use !.
  582. form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
  583. }
  584. form_set_value($element, $value, $form_state);
  585. // dsm($element, '$element afetr form_set_value');
  586. return $element;
  587. }else{
  588. # if the field was not in the form
  589. $values = array();
  590. foreach ($element['#default_value'] as $tid) {
  591. $values[] = (array) taxonomy_term_load($tid);
  592. }
  593. form_set_value($element, $values, $form_state);
  594. // dsm($element, '$element afetr form_set_value');
  595. return $element;
  596. }
  597. }
  598. /**
  599. * Returns an array of allowed values defined by the given view.
  600. *
  601. * @param $filter
  602. * A view, in the format VIEWNAME:DISPLAYNAME
  603. *
  604. * @return
  605. * An array of term IDs (tid => true) returned by the view.
  606. */
  607. function _term_reference_tree_get_allowed_values($filter) {
  608. $viewname = "";
  609. $displayname = "";
  610. $allowed = array();
  611. if (module_exists('views') && $filter != '') {
  612. list($viewname, $displayname) = explode(":", $filter);
  613. $view = views_get_view($viewname);
  614. if (is_object($view)) {
  615. if ($view->access($displayname)) {
  616. // Save the page title first, since execute_display() will reset this to the display title.
  617. $title = drupal_get_title();
  618. $view->execute_display($displayname);
  619. $title = drupal_set_title($title, PASS_THROUGH);
  620. foreach($view->result as $item) {
  621. $allowed[$item->tid] = true;
  622. }
  623. }
  624. else {
  625. drupal_set_message("Cannot access view for term reference tree widget.", 'warning');
  626. }
  627. }
  628. else {
  629. drupal_set_message("Term reference tree: no view named '$viewname'", 'warning');
  630. }
  631. }
  632. return $allowed;
  633. }
  634. /**
  635. * Builds a single item in the term reference tree widget.
  636. *
  637. * This function returns an element with a checkbox for a single taxonomy term.
  638. * If that term has children, it appends checkbox_tree_level element that
  639. * contains the children. It is meant to be called recursively when the widget
  640. * is built.
  641. *
  642. * @param $element
  643. * The main checkbox_tree element.
  644. * @param $term
  645. * A taxonomy term object. $term->children should be an array of the term
  646. * objects that are that term's children.
  647. * @param $form_state
  648. * The form state.
  649. * @param $value
  650. * The value of the element.
  651. * @param $max_choices
  652. * The maximum number of allowed selections.
  653. *
  654. * @return
  655. * A completed checkbox_tree_item element, which contains a checkbox and
  656. * possibly a checkbox_tree_level element as well.
  657. */
  658. function _term_reference_tree_build_item(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $parent, $depth) {
  659. $start_minimized = FALSE;
  660. if (array_key_exists('#start_minimized', $element)) {
  661. $start_minimized = $element['#start_minimized'];
  662. }
  663. $leaves_only = FALSE;
  664. if (array_key_exists('#leaves_only', $element)) {
  665. $leaves_only = $element['#leaves_only'];
  666. }
  667. $t = null;
  668. // if(module_exists('locale')) {
  669. // $t = taxonomy_term_load($term->tid);
  670. // taxonomy_term_load return term without name, because of module title
  671. // $term_name = entity_label('taxonomy_term', $term);
  672. // there is a problem here with title module, title_entity_label() return empty label
  673. // see http://drupal.org/node/1764354
  674. // } else {
  675. $term_name = $term->name;
  676. // }
  677. $container = array(
  678. '#type' => 'checkbox_tree_item',
  679. '#max_choices' => $max_choices,
  680. '#leaves_only' => $leaves_only,
  681. '#term_name' => $term_name,
  682. '#level_start_minimized' => FALSE,
  683. '#depth' => $depth,
  684. );
  685. if ((!$element['#leaves_only'] || count($term->children) == 0) && $depth >= $element['#starting_depth']) {
  686. $name = "edit-" . str_replace('_', '-', $element['#field_name']);
  687. $e = array(
  688. '#type' => ($max_choices == 1) ? 'radio' : 'checkbox',
  689. '#title' => $term_name,
  690. '#on_value' => $term->tid,
  691. '#off_value' => 0,
  692. '#return_value' => $term->tid,
  693. '#parent_values' => $parent_tids,
  694. '#default_value' => isset($value[$term->tid]) ? $term->tid : NULL,
  695. '#attributes' => isset($element['#attributes']) ? $element['#attributes'] : NULL,
  696. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  697. );
  698. if ($element['#token_display'] != '' && module_exists('token')) {
  699. if(!$t) {
  700. $t = taxonomy_term_load($term->tid);
  701. }
  702. $e['#title'] = token_replace($element['#token_display'], array('term' => $t), array('clear' => TRUE));
  703. }
  704. if ($e['#type'] == 'radio') {
  705. $parents_for_id = array_merge($element['#parents'], array($term->tid));
  706. $e['#id'] = drupal_html_id('edit-' . implode('-', $parents_for_id));
  707. $e['#parents'] = $element['#parents'];
  708. }else if($element['#track_list_order']){
  709. $delta = 0;
  710. $i = -1;
  711. if(isset($value[$term->tid])){
  712. foreach ($value as $tid) {
  713. $i++;
  714. if($term->tid == $tid)
  715. break;
  716. }
  717. }
  718. $e_weight = array(
  719. '#type' => 'hidden',
  720. '#value' => $i,
  721. '#name' => $term->tid.'-weight',
  722. );
  723. }
  724. }
  725. else {
  726. $e = array(
  727. '#type' => 'checkbox_tree_label',
  728. '#value' => $term_name,
  729. );
  730. }
  731. $container[$term->tid] = $e;
  732. if(isset($e_weight)){
  733. $container[$term->tid.'-weight'] = $e_weight;
  734. }
  735. if (($depth + 1 <= $element['#max_depth'] || !$element['#max_depth']) && property_exists($term, 'children') && count($term->children) > 0) {
  736. $parents = $parent_tids;
  737. $parents[] = $term->tid;
  738. $container[$term->tid . '-children'] = _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $starting_depth, $parents, $depth+1);
  739. $container['#level_start_minimized'] = $container[$term->tid . '-children']['#level_start_minimized'];
  740. }
  741. return $container;
  742. }
  743. /**
  744. * Builds a level in the term reference tree widget.
  745. *
  746. * This function returns an element that has a number of checkbox_tree_item elements
  747. * as children. It is meant to be called recursively when the widget is built.
  748. *
  749. * @param $element
  750. * The main checkbox_tree element.
  751. * @param $term
  752. * A taxonomy term object. $term->children should be an array of the term
  753. * objects that are that term's children.
  754. * @param $form_state
  755. * The form state.
  756. * @param $value
  757. * The value of the element.
  758. * @param $max_choices
  759. * The maximum number of allowed selections.
  760. *
  761. * @return
  762. * A completed checkbox_tree_level element.
  763. */
  764. function _term_reference_tree_build_level(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $depth) {
  765. $start_minimized = FALSE;
  766. if (array_key_exists('#start_minimized', $element)) {
  767. $start_minimized = $element['#start_minimized'];
  768. }
  769. $leaves_only = FALSE;
  770. if (array_key_exists('#leaves_only', $element)) {
  771. $leaves_only = $element['#leaves_only'];
  772. }
  773. $container = array(
  774. '#type' => 'checkbox_tree_level',
  775. '#max_choices' => $max_choices,
  776. '#leaves_only' => $leaves_only,
  777. '#start_minimized' => $start_minimized,
  778. '#depth' => $depth,
  779. );
  780. $container['#level_start_minimized'] = $depth > 1 && $element['#start_minimized'] && !($term->children_selected);
  781. foreach($term->children as $t) {
  782. $container[$t->tid] = _term_reference_tree_build_item($element, $t, $form_state, $value, $max_choices, $starting_depth, $parent_tids, $container, $depth);
  783. }
  784. return $container;
  785. }