term_reference_tree.widget.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. $element = $variables['element'];
  402. $output = "<div class='parent-term'>" . $element['#value'] . "</div>";
  403. return $output;
  404. }
  405. /**
  406. * Shows a list of items that have been checked.
  407. * The display happens on the client-side.
  408. * Use this function to theme the element's label,
  409. * and the "nothing selected" message.
  410. *
  411. * @param $variables Variables available for theming.
  412. */
  413. function theme_checkbox_tree_track_list($variables) {
  414. //Should the label be singular or plural? Depends on cardinality of term field.
  415. static $nothingselected;
  416. // dsm($variables, 'theme_checkbox_tree_track_list : $variables');
  417. if(!$nothingselected) {
  418. $nothingselected = t('[Nothing selected]');
  419. //Add the "Nothing selected" text. To style it, replace it with whatever you want.
  420. //Could do this with a file instead.
  421. drupal_add_js(
  422. 'var termReferenceTreeNothingSelectedText = "' . $nothingselected . '";',
  423. 'inline'
  424. );
  425. }
  426. $label = format_plural(
  427. $variables['element']['#max_choices'],
  428. 'Selected item (click the item to uncheck it)',
  429. 'Selected items (click an item to uncheck it)'
  430. );
  431. $order = $variables['element']['#track_list_order'] ? 'order-list' : '';
  432. $output =
  433. '<div class="term-reference-track-list-container">
  434. <div class="term-reference-track-list-label">' . $label . '</div>
  435. <ul class="term-reference-tree-track-list '.$order.'"><li class="term_ref_tree_nothing_message">'.$nothingselected.'</li></ul>
  436. </div>';
  437. return $output;
  438. }
  439. /**
  440. * Implements hook_widget_field_form().
  441. */
  442. function term_reference_tree_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  443. $settings = $instance['widget']['settings'];
  444. $voc = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
  445. $path = drupal_get_path('module', 'term_reference_tree');
  446. $value_key = key($field['columns']);
  447. $type = $instance['widget']['type'];
  448. $default_value = array();
  449. foreach($items as $item) {
  450. $key = $item[$value_key];
  451. if ($key === 0) {
  452. $default_value[$key] = '0';
  453. }
  454. else {
  455. $default_value[$key] = $key;
  456. }
  457. }
  458. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  459. $properties = array();
  460. if (!array_key_exists('#value', $element))
  461. $element['#value'] = array();
  462. // A switch statement, in case we ever add more widgets to this module.
  463. switch($instance['widget']['type']) {
  464. case 'term_reference_tree':
  465. $element['#attached']['js'] = array($path . '/term_reference_tree.js');
  466. $element['#attached']['css'] = array($path . '/term_reference_tree.css');
  467. $element['#type'] = 'checkbox_tree';
  468. $element['#default_value'] = $multiple ? $default_value : array(reset($default_value) => reset($default_value));
  469. $element['#max_choices'] = $field['cardinality'];
  470. $element['#max_depth'] = $settings['max_depth'];
  471. $element['#starting_depth'] = $settings['starting_depth'];
  472. $element['#start_minimized'] = $settings['start_minimized'];
  473. $element['#leaves_only'] = $settings['leaves_only'];
  474. $element['#filter_view'] = module_exists('views') ? $settings['filter_view'] : '';
  475. $element['#select_parents'] = $settings['select_parents'];
  476. $element['#cascading_selection'] = $settings['cascading_selection'];
  477. $element['#track_list'] = $settings['track_list'];
  478. $element['#track_list_order'] = $settings['track_list_order'];
  479. $element['#parent_tid'] = $settings['parent_term_id'] || $field['settings']['allowed_values'][0]['parent'];
  480. $element['#vocabulary'] = $voc->vid;
  481. $element['#token_display'] = module_exists('token') ? $settings['token_display'] : '';
  482. break;
  483. }
  484. $element += array(
  485. '#value_key' => $value_key,
  486. '#element_validate' => array('_term_reference_tree_widget_validate'),
  487. '#properties' => $properties,
  488. );
  489. if ($settings['track_list_order']) {
  490. drupal_add_library('system', 'ui.sortable');
  491. }
  492. return $element;
  493. }
  494. /**
  495. * Validates the term reference tree widgets.
  496. *
  497. * This function sets the value of the tree widgets into a form that Drupal
  498. * can understand, and also checks if the field is required and has been
  499. * left empty.
  500. *
  501. * @param $element
  502. * The element to be validated.
  503. * @param $form_state
  504. * The state of the form.
  505. *
  506. * @return
  507. * The validated element.
  508. */
  509. function _term_reference_tree_widget_validate(&$element, &$form_state) {
  510. // dsm($element, '$element');
  511. // dsm($form_state, '$form_state');
  512. # if the field was in the form
  513. if(isset($form_state['input'][$element['#field_name']])){
  514. $items = _term_reference_tree_flatten($element, $form_state);
  515. $value = array();
  516. if ($element['#max_choices'] != 1) {
  517. if(!$element['#track_list_order']){
  518. foreach($items as $child) {
  519. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  520. array_push($value, array( $element['#value_key'] => $child['#value']));
  521. // If the element is leaves only and select parents is on, then automatically
  522. // add all the parents of each selected value.
  523. if ($element['#select_parents'] && $element['#leaves_only']) {
  524. foreach($child['#parent_values'] as $parent_tid) {
  525. if (!in_array(array($element['#value_key'] => $parent_tid), $value)) {
  526. array_push($value, array($element['#value_key'] => $parent_tid));
  527. }
  528. }
  529. }
  530. }
  531. }
  532. }else{
  533. $selected_terms = array();
  534. $deltas = array();
  535. foreach($items as $child) {
  536. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  537. $selected_terms[] = array(
  538. "delta" => $form_state['input'][$child['#value'].'-weight'],
  539. "term" => array($element['#value_key'] => $child['#value']),
  540. );
  541. // If the element is leaves only and select parents is on, then automatically
  542. // add all the parents of each selected value.
  543. if ($element['#select_parents'] && $element['#leaves_only']) {
  544. foreach($child['#parent_values'] as $parent_tid) {
  545. if (!in_array(array($element['#value_key'] => $parent_tid), $selected_terms)) {
  546. $selected_terms[] = array(
  547. "delta" => $form_state['input'][$parent_tid.'-weight'],
  548. "term" => array($element['#value_key'] => $child['#value']),
  549. );
  550. }
  551. }
  552. }
  553. }
  554. }
  555. // dsm($deltas, '$deltas');
  556. // dsm($selected_terms, '$selected_terms before sort');
  557. // reorder items
  558. function delta_sort($a, $b){
  559. return $a['delta'] > $b['delta'];
  560. }
  561. usort($selected_terms, "delta_sort");
  562. // dsm($selected_terms, '$selected_terms after sort');
  563. // record in value
  564. foreach ($selected_terms as $selected_term) {
  565. $value[] = $selected_term['term'];
  566. }
  567. }
  568. }
  569. else {
  570. // If it's a tree of radio buttons, they all have the same value, so we can just
  571. // grab the value of the first one.
  572. if (count($items) > 0) {
  573. $child = reset($items);
  574. if (array_key_exists('#value', $child) && $child['#value'] !== 0) {
  575. array_push($value, array($element['#value_key'] => $child['#value']));
  576. }
  577. }
  578. }
  579. if ($element['#required'] && empty($value)) {
  580. // The title is already check_plained so it's appropriate to use !.
  581. form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
  582. }
  583. form_set_value($element, $value, $form_state);
  584. // dsm($element, '$element afetr form_set_value');
  585. return $element;
  586. }else{
  587. # if the field was not in the form
  588. $values = array();
  589. foreach ($element['#default_value'] as $tid) {
  590. $values[] = (array) taxonomy_term_load($tid);
  591. }
  592. form_set_value($element, $values, $form_state);
  593. // dsm($element, '$element afetr form_set_value');
  594. return $element;
  595. }
  596. }
  597. /**
  598. * Returns an array of allowed values defined by the given view.
  599. *
  600. * @param $filter
  601. * A view, in the format VIEWNAME:DISPLAYNAME
  602. *
  603. * @return
  604. * An array of term IDs (tid => true) returned by the view.
  605. */
  606. function _term_reference_tree_get_allowed_values($filter) {
  607. $viewname = "";
  608. $displayname = "";
  609. $allowed = array();
  610. if (module_exists('views') && $filter != '') {
  611. list($viewname, $displayname) = explode(":", $filter);
  612. $view = views_get_view($viewname);
  613. if (is_object($view)) {
  614. if ($view->access($displayname)) {
  615. // Save the page title first, since execute_display() will reset this to the display title.
  616. $title = drupal_get_title();
  617. $view->execute_display($displayname);
  618. $title = drupal_set_title($title, PASS_THROUGH);
  619. foreach($view->result as $item) {
  620. $allowed[$item->tid] = true;
  621. }
  622. }
  623. else {
  624. drupal_set_message("Cannot access view for term reference tree widget.", 'warning');
  625. }
  626. }
  627. else {
  628. drupal_set_message("Term reference tree: no view named '$viewname'", 'warning');
  629. }
  630. }
  631. return $allowed;
  632. }
  633. /**
  634. * Builds a single item in the term reference tree widget.
  635. *
  636. * This function returns an element with a checkbox for a single taxonomy term.
  637. * If that term has children, it appends checkbox_tree_level element that
  638. * contains the children. It is meant to be called recursively when the widget
  639. * is built.
  640. *
  641. * @param $element
  642. * The main checkbox_tree element.
  643. * @param $term
  644. * A taxonomy term object. $term->children should be an array of the term
  645. * objects that are that term's children.
  646. * @param $form_state
  647. * The form state.
  648. * @param $value
  649. * The value of the element.
  650. * @param $max_choices
  651. * The maximum number of allowed selections.
  652. *
  653. * @return
  654. * A completed checkbox_tree_item element, which contains a checkbox and
  655. * possibly a checkbox_tree_level element as well.
  656. */
  657. function _term_reference_tree_build_item(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $parent, $depth) {
  658. $start_minimized = FALSE;
  659. if (array_key_exists('#start_minimized', $element)) {
  660. $start_minimized = $element['#start_minimized'];
  661. }
  662. $leaves_only = FALSE;
  663. if (array_key_exists('#leaves_only', $element)) {
  664. $leaves_only = $element['#leaves_only'];
  665. }
  666. $t = null;
  667. if(module_exists('locale')) {
  668. $t = taxonomy_term_load($term->tid);
  669. $term_name = entity_label('taxonomy_term', $t);
  670. } else {
  671. $term_name = $term->name;
  672. }
  673. $container = array(
  674. '#type' => 'checkbox_tree_item',
  675. '#max_choices' => $max_choices,
  676. '#leaves_only' => $leaves_only,
  677. '#term_name' => $term_name,
  678. '#level_start_minimized' => FALSE,
  679. '#depth' => $depth,
  680. );
  681. if ((!$element['#leaves_only'] || count($term->children) == 0) && $depth >= $element['#starting_depth']) {
  682. $name = "edit-" . str_replace('_', '-', $element['#field_name']);
  683. $e = array(
  684. '#type' => ($max_choices == 1) ? 'radio' : 'checkbox',
  685. '#title' => $term_name,
  686. '#on_value' => $term->tid,
  687. '#off_value' => 0,
  688. '#return_value' => $term->tid,
  689. '#parent_values' => $parent_tids,
  690. '#default_value' => isset($value[$term->tid]) ? $term->tid : NULL,
  691. '#attributes' => isset($element['#attributes']) ? $element['#attributes'] : NULL,
  692. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  693. );
  694. if ($element['#token_display'] != '' && module_exists('token')) {
  695. if(!$t) {
  696. $t = taxonomy_term_load($term->tid);
  697. }
  698. $e['#title'] = token_replace($element['#token_display'], array('term' => $t), array('clear' => TRUE));
  699. }
  700. if ($e['#type'] == 'radio') {
  701. $parents_for_id = array_merge($element['#parents'], array($term->tid));
  702. $e['#id'] = drupal_html_id('edit-' . implode('-', $parents_for_id));
  703. $e['#parents'] = $element['#parents'];
  704. }else if($element['#track_list_order']){
  705. $delta = 0;
  706. $i = -1;
  707. if(isset($value[$term->tid])){
  708. foreach ($value as $tid) {
  709. $i++;
  710. if($term->tid == $tid)
  711. break;
  712. }
  713. }
  714. $e_weight = array(
  715. '#type' => 'hidden',
  716. '#value' => $i,
  717. '#name' => $term->tid.'-weight',
  718. );
  719. }
  720. }
  721. else {
  722. $e = array(
  723. '#type' => 'checkbox_tree_label',
  724. '#value' => $term_name,
  725. );
  726. }
  727. $container[$term->tid] = $e;
  728. if(isset($e_weight)){
  729. $container[$term->tid.'-weight'] = $e_weight;
  730. }
  731. if (($depth + 1 <= $element['#max_depth'] || !$element['#max_depth']) && property_exists($term, 'children') && count($term->children) > 0) {
  732. $parents = $parent_tids;
  733. $parents[] = $term->tid;
  734. $container[$term->tid . '-children'] = _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $starting_depth, $parents, $depth+1);
  735. $container['#level_start_minimized'] = $container[$term->tid . '-children']['#level_start_minimized'];
  736. }
  737. return $container;
  738. }
  739. /**
  740. * Builds a level in the term reference tree widget.
  741. *
  742. * This function returns an element that has a number of checkbox_tree_item elements
  743. * as children. It is meant to be called recursively when the widget is built.
  744. *
  745. * @param $element
  746. * The main checkbox_tree element.
  747. * @param $term
  748. * A taxonomy term object. $term->children should be an array of the term
  749. * objects that are that term's children.
  750. * @param $form_state
  751. * The form state.
  752. * @param $value
  753. * The value of the element.
  754. * @param $max_choices
  755. * The maximum number of allowed selections.
  756. *
  757. * @return
  758. * A completed checkbox_tree_level element.
  759. */
  760. function _term_reference_tree_build_level(&$element, &$term, &$form_state, &$value, $max_choices, $starting_depth, $parent_tids, $depth) {
  761. $start_minimized = FALSE;
  762. if (array_key_exists('#start_minimized', $element)) {
  763. $start_minimized = $element['#start_minimized'];
  764. }
  765. $leaves_only = FALSE;
  766. if (array_key_exists('#leaves_only', $element)) {
  767. $leaves_only = $element['#leaves_only'];
  768. }
  769. $container = array(
  770. '#type' => 'checkbox_tree_level',
  771. '#max_choices' => $max_choices,
  772. '#leaves_only' => $leaves_only,
  773. '#start_minimized' => $start_minimized,
  774. '#depth' => $depth,
  775. );
  776. $container['#level_start_minimized'] = $depth > 1 && $element['#start_minimized'] && !($term->children_selected);
  777. foreach($term->children as $t) {
  778. $container[$t->tid] = _term_reference_tree_build_item($element, $t, $form_state, $value, $max_choices, $starting_depth, $parent_tids, $container, $depth);
  779. }
  780. return $container;
  781. }