autocomplete_deluxe.module 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. /**
  3. * @file
  4. * Define enhanced autocomplete wdiget.
  5. */
  6. /**
  7. * Implements hook_field_info().
  8. */
  9. function autocomplete_deluxe_field_widget_info() {
  10. return array(
  11. 'autocomplete_deluxe_taxonomy' => array(
  12. 'label' => t('Autocomplete Deluxe'),
  13. 'field types' => array('taxonomy_term_reference'),
  14. 'settings' => array(
  15. 'size' => 60,
  16. 'autocomplete_deluxe_path' => 'autocomplete_deluxe/taxonomy',
  17. ),
  18. 'behaviors' => array(
  19. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  20. ),
  21. ),
  22. );
  23. }
  24. /**
  25. * Custom taxonomy callback, which also accepts an empty string search.
  26. */
  27. function taxonomy_autocomplete_deluxe($field_name, $tags_typed = '', $limit = 10) {
  28. $field = field_info_field($field_name);
  29. $use_synonyms = !empty($_GET['synonyms']);
  30. // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  31. $tags_typed = drupal_explode_tags($tags_typed);
  32. $tag_last = drupal_strtolower(array_pop($tags_typed));
  33. $matches = array();
  34. // Part of the criteria for the query come from the field's own settings.
  35. $vids = array();
  36. $vocabularies = taxonomy_vocabulary_get_names();
  37. foreach ($field['settings']['allowed_values'] as $tree) {
  38. // If the content taxonomy setting content_taxonomy_ignore_in_suggestions
  39. // is set, then the vocabulary is ignored.
  40. if (empty($tree['content_taxonomy_ignore_in_suggestions'])) {
  41. $vids[] = $vocabularies[$tree['vocabulary']]->vid;
  42. }
  43. }
  44. $query = db_select('taxonomy_term_data', 't');
  45. $query->addTag('translatable');
  46. $query->addTag('term_access');
  47. if (module_exists('synonyms') && !empty($use_synonyms)) {
  48. $query->leftJoin('field_data_synonyms_synonym', 'fdss', 'fdss.entity_id = t.tid');
  49. }
  50. if ($tag_last != '') {
  51. // Do not select already entered terms.
  52. if (!empty($tags_typed)) {
  53. $query->condition('t.name', $tags_typed, 'NOT IN');
  54. }
  55. // Select rows that match by term name.
  56. $query
  57. ->fields('t', array('tid', 'name'))
  58. ->condition('t.vid', $vids);
  59. if (module_exists('synonyms') && !empty($use_synonyms)) {
  60. $or = db_or();
  61. $or->condition('fdss.synonyms_synonym_value', '%' . db_like($tag_last) . '%', 'LIKE');
  62. $or->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE');
  63. $query->condition($or);
  64. }
  65. else {
  66. $query->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE');
  67. }
  68. if (isset($limit) && $limit > 0) {
  69. $query->range(0, $limit);
  70. }
  71. $tags_return = $query->execute()
  72. ->fetchAllKeyed();
  73. }
  74. else {
  75. $query
  76. ->fields('t', array('tid', 'name'))
  77. ->condition('t.vid', $vids);
  78. if (isset($limit) && $limit > 0) {
  79. $query->range(0, $limit);
  80. }
  81. $tags_return = $query->execute()
  82. ->fetchAllKeyed();
  83. }
  84. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  85. $term_matches = array();
  86. foreach ($tags_return as $tid => $name) {
  87. $n = $name;
  88. // Term names containing commas or quotes must be wrapped in quotes.
  89. if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  90. $n = '"' . str_replace('"', '""', $name) . '"';
  91. }
  92. $term_matches[$prefix . $n] = check_plain($name);
  93. }
  94. drupal_json_output($term_matches);
  95. }
  96. /**
  97. * Returns all allowed terms for a field without any prefix.
  98. */
  99. function autocomplete_deluxe_allowed_terms($field) {
  100. $options = array();
  101. foreach ($field['settings']['allowed_values'] as $tree) {
  102. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  103. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
  104. foreach ($terms as $term) {
  105. $options[$term->name] = $term->name;
  106. }
  107. }
  108. }
  109. }
  110. return $options;
  111. }
  112. /**
  113. * Implements hook_field_widget_settings_form().
  114. */
  115. function autocomplete_deluxe_field_widget_settings_form($field, $instance) {
  116. $widget = $instance['widget'];
  117. $settings = $widget['settings'];
  118. $form['size'] = array(
  119. '#type' => 'textfield',
  120. '#title' => t('Size of textfield'),
  121. '#default_value' => isset($settings['size']) ? $settings['size'] : 6,
  122. '#element_validate' => array('_element_validate_integer_positive'),
  123. '#required' => TRUE,
  124. );
  125. $form['limit'] = array(
  126. '#type' => 'textfield',
  127. '#title' => t('Limit of the output.'),
  128. '#description' => t('If set to zero no limit will be used'),
  129. '#default_value' => isset($settings['limit']) ? $settings['limit'] : 10,
  130. '#element_validate' => array('_element_validate_integer'),
  131. );
  132. $form['min_length'] = array(
  133. '#type' => 'textfield',
  134. '#title' => t('Mininum length.'),
  135. '#description' => t('The minimum length of characters to enter to open the suggestion list.'),
  136. '#default_value' => isset($settings['min_length']) ? $settings['min_length'] : 0,
  137. '#element_validate' => array('_element_validate_integer'),
  138. );
  139. $form['delimiter'] = array(
  140. '#type' => 'textfield',
  141. '#title' => t('Delimiter.'),
  142. '#description' => t('A character which should be used beside the enter key, to seperate terms.'),
  143. '#default_value' => isset($settings['delimiter']) ? $settings['delimiter'] : '',
  144. '#size' => 1,
  145. );
  146. if (module_exists('synonyms')) {
  147. $form['use_synonyms'] = array(
  148. '#type' => 'checkbox',
  149. '#title' => t('Allow synonyms'),
  150. '#description' => t('Should users be able to search for synonyms of terms?'),
  151. '#default_value' => isset($settings['use_synonyms']) ? $settings['use_synonyms'] : FALSE,
  152. );
  153. }
  154. return $form;
  155. }
  156. /**
  157. * Implodes the tags from the taxonomy module.
  158. *
  159. * This function is essentially the same as axonomy_implode_tags, with the
  160. * difference, that it uses only a comma instead of a comma and a space to
  161. * implode the tags. It will help keep problems with delimiters to a minimum.
  162. */
  163. function autocomplete_deluxe_taxonomy_implode_tags($tags, $vid = NULL) {
  164. $typed_tags = array();
  165. foreach ($tags as $tag) {
  166. // Extract terms belonging to the vocabulary in question.
  167. if (!isset($vid) || $tag->vid == $vid) {
  168. // Make sure we have a completed loaded taxonomy term.
  169. if (isset($tag->name)) {
  170. // Commas and quotes in tag names are special cases, so encode 'em.
  171. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  172. $tag->name = '"' . str_replace('"', '""', $tag->name) . '"';
  173. }
  174. $typed_tags[] = $tag->name;
  175. }
  176. }
  177. }
  178. return implode(',', $typed_tags);
  179. }
  180. /**
  181. * Implements hook_field_widget_error().
  182. */
  183. function autocomplete_deluxe_field_widget_error($element, $error, $form, &$form_state) {
  184. form_error($element, $error['message']);
  185. }
  186. /**
  187. * Implements hook_field_widget_form().
  188. */
  189. function autocomplete_deluxe_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  190. $element += array(
  191. '#type' => 'autocomplete_deluxe',
  192. '#size' => $instance['widget']['settings']['size'],
  193. '#limit' => isset($instance['widget']['settings']['limit']) ? $instance['widget']['settings']['limit'] : 10,
  194. '#min_length' => isset($instance['widget']['settings']['min_length']) ? $instance['widget']['settings']['min_length'] : 0,
  195. '#use_synonyms' =>isset($instance['widget']['settings']['use_synonyms']) ? $instance['widget']['settings']['use_synonyms'] : 0,
  196. '#delimiter' =>isset($instance['widget']['settings']['delimiter']) ? $instance['widget']['settings']['delimiter'] : '',
  197. );
  198. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED ? TRUE : FALSE;
  199. $tags = array();
  200. foreach ($items as $item) {
  201. $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  202. }
  203. $element['#element_validate'] = array('taxonomy_autocomplete_validate');
  204. $element += array(
  205. '#multiple' => $multiple,
  206. '#autocomplete_deluxe_path' => url($instance['widget']['settings']['autocomplete_deluxe_path'] . '/' . $field['field_name'], array('absolute' => TRUE)),
  207. '#default_value' => autocomplete_deluxe_taxonomy_implode_tags($tags),
  208. );
  209. return $element;
  210. }
  211. /**
  212. * Generates the basic form elements and javascript settings.
  213. */
  214. function autocomplete_deluxe_element_process($element) {
  215. $element['#attached'] = array(
  216. 'library' => array(array('system', 'ui.autocomplete'), array('system', 'ui.button')),
  217. 'js' => array(drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.js'),
  218. 'css' => array(drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.css'),
  219. );
  220. // Workaround for problems with jquery css in seven theme.
  221. if ($GLOBALS['theme'] == 'seven') {
  222. $element['#attached']['css'][] = drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.seven.css';
  223. }
  224. $html_id = drupal_html_id('autocomplete-deluxe-input');
  225. $element['#after_build'][] = 'autocomplete_deluxe_after_build';
  226. // Set default options for multiple values.
  227. $element['#multiple'] = isset($element['#multiple']) ? $element['#multiple'] : FALSE;
  228. $element['textfield'] = array(
  229. '#type' => 'textfield',
  230. '#size' => isset($element['#size']) ? $element['#size'] : '',
  231. '#attributes' => array('class' => array('autocomplete-deluxe-form'), 'id' => array($html_id)),
  232. '#default_value' => '',
  233. '#prefix' => '<div class="autocomplete-deluxe-container">',
  234. '#suffix' => '</div>',
  235. );
  236. $js_settings['autocomplete_deluxe'][$html_id] = array(
  237. 'input_id' => $html_id,
  238. 'multiple' => $element['#multiple'],
  239. 'required' => $element['#required'],
  240. 'limit' => isset($element['#limit']) ? $element['#limit'] : 10,
  241. 'min_length' => isset($element['#min_length']) ? $element['#min_length'] : 0,
  242. 'use_synonyms' => isset($element['#use_synonyms']) ? $element['#use_synonyms'] : 0,
  243. 'delimiter' => isset($element['#delimiter']) ? $element['#delimiter'] : '',
  244. );
  245. if (isset($element['#autocomplete_deluxe_path'])) {
  246. if (isset($element['#default_value'])) {
  247. // Split on the comma only if that comma has zero, or an even number of
  248. // quotes in ahead of it.
  249. // http://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes
  250. $default_value = preg_replace('/,(?=([^\"]*\"[^\"]*\")*[^\"]*$)/i', '"" ""', $element['#default_value']);
  251. $default_value = '""' . $default_value . '""';
  252. }
  253. else {
  254. $default_value = '';
  255. }
  256. if ($element['#multiple']) {
  257. $element['value_field'] = array(
  258. '#type' => 'textfield',
  259. '#attributes' => array('class' => array('autocomplete-deluxe-value-field')),
  260. '#default_value' => $default_value,
  261. '#prefix' => '<div class="autocomplete-deluxe-value-container">',
  262. '#suffix' => '</div>',
  263. );
  264. $element['textfield']['#attributes']['style'] = array('display:none');
  265. }
  266. else {
  267. $element['textfield']['#default_value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  268. }
  269. $js_settings['autocomplete_deluxe'][$html_id] += array(
  270. 'type' => 'ajax',
  271. 'uri' => $element['#autocomplete_deluxe_path'],
  272. );
  273. }
  274. else {
  275. // If there is no source (path or data), we don't want to add the js
  276. // settings and so the functions will be abborted.
  277. return $element;
  278. }
  279. $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
  280. $element['#tree'] = TRUE;
  281. return $element;
  282. }
  283. /**
  284. * Helper function to determine the value for a autocomplete deluxe form
  285. * element.
  286. */
  287. function autocomplete_deluxe_value(&$element, $input = FALSE, $form_state = NULL) {
  288. // This runs before child elements are processed, so we cannot calculate the
  289. // value here. But we have to make sure the value is an array, so the form
  290. // API is able to proccess the children to set their values in the array. Thus
  291. // once the form API has finished processing the element, the value is an
  292. // array containing the child element values. Then finally the after build
  293. // callback converts it back to the numeric value and sets that.
  294. return array();
  295. }
  296. /**
  297. * FAPI after build callback for the duration parameter type form.
  298. * Fixes up the form value by applying the multiplier.
  299. */
  300. function autocomplete_deluxe_after_build($element, &$form_state) {
  301. // By default drupal sets the maxlength to 128 if the property isn't
  302. // specified, but since the limit isn't useful in some cases,
  303. // we unset the property.
  304. unset($element['textfield']['#maxlength']);
  305. // Set the elements value from either the value field or text field input.
  306. $element['#value'] = isset($element['value_field']) ? $element['value_field']['#value'] : $element['textfield']['#value'];
  307. if (isset($element['value_field'])) {
  308. $element['#value'] = trim($element['#value']);
  309. // Replace all double double quotes and space with a comma. This will allows
  310. // us to keep entries in double quotes.
  311. $element['#value'] = str_replace('"" ""', ',', $element['#value']);
  312. $element['#value'] = str_replace('"" ""', ',', $element['#value']);
  313. // Remove the double quotes at the beginning and the end from the first and
  314. // the last term.
  315. $element['#value'] = substr($element['#value'], 2, strlen($element['#value']) - 4);
  316. unset($element['value_field']['#maxlength']);
  317. }
  318. form_set_value($element, $element['#value'], $form_state);
  319. return $element;
  320. }
  321. /**
  322. * Implements hook_element_info().
  323. */
  324. function autocomplete_deluxe_element_info() {
  325. $types['autocomplete_deluxe'] = array(
  326. '#input' => TRUE,
  327. '#value_callback' => 'autocomplete_deluxe_value',
  328. '#pre_render' => array('form_pre_render_conditional_form_element'),
  329. '#process' => array('autocomplete_deluxe_element_process'),
  330. );
  331. return $types;
  332. }
  333. /**
  334. * Implements hook_menu().
  335. */
  336. function autocomplete_deluxe_menu() {
  337. $items['autocomplete_deluxe/taxonomy'] = array(
  338. 'title' => 'Autocomplete deluxe taxonomy',
  339. 'page callback' => 'taxonomy_autocomplete_deluxe',
  340. 'access arguments' => array('access content'),
  341. 'type' => MENU_CALLBACK,
  342. );
  343. return $items;
  344. }