autocomplete_deluxe.module 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 autocomplete_deluxe_taxonomy_callback($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. $form['not_found_message'] = array(
  147. '#type' => 'textfield',
  148. '#title' => t('Term not found message.'),
  149. '#description' => t('A message text which will be displayed, if the entered term was not found.'),
  150. '#default_value' => isset($settings['not_found_message']) ? $settings['not_found_message'] : "The term '@term' will be added.",
  151. );
  152. if (module_exists('synonyms')) {
  153. $form['use_synonyms'] = array(
  154. '#type' => 'checkbox',
  155. '#title' => t('Allow synonyms'),
  156. '#description' => t('Should users be able to search for synonyms of terms?'),
  157. '#default_value' => isset($settings['use_synonyms']) ? $settings['use_synonyms'] : FALSE,
  158. );
  159. }
  160. return $form;
  161. }
  162. /**
  163. * Implodes the tags from the taxonomy module.
  164. *
  165. * This function is essentially the same as axonomy_implode_tags, with the
  166. * difference, that it uses only a comma instead of a comma and a space to
  167. * implode the tags. It will help keep problems with delimiters to a minimum.
  168. */
  169. function autocomplete_deluxe_taxonomy_implode_tags($tags, $vid = NULL) {
  170. $typed_tags = array();
  171. foreach ($tags as $tag) {
  172. // Extract terms belonging to the vocabulary in question.
  173. if (!isset($vid) || $tag->vid == $vid) {
  174. // Make sure we have a completed loaded taxonomy term.
  175. if (isset($tag->name)) {
  176. // Commas and quotes in tag names are special cases, so encode 'em.
  177. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  178. $tag->name = '"' . str_replace('"', '""', $tag->name) . '"';
  179. }
  180. $typed_tags[] = $tag->name;
  181. }
  182. }
  183. }
  184. return implode(',', $typed_tags);
  185. }
  186. /**
  187. * Implements hook_field_widget_error().
  188. */
  189. function autocomplete_deluxe_field_widget_error($element, $error, $form, &$form_state) {
  190. form_error($element, $error['message']);
  191. }
  192. /**
  193. * Implements hook_field_widget_form().
  194. */
  195. function autocomplete_deluxe_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  196. $element += array(
  197. '#type' => 'autocomplete_deluxe',
  198. '#size' => $instance['widget']['settings']['size'],
  199. '#limit' => isset($instance['widget']['settings']['limit']) ? $instance['widget']['settings']['limit'] : 10,
  200. '#min_length' => isset($instance['widget']['settings']['min_length']) ? $instance['widget']['settings']['min_length'] : 0,
  201. '#use_synonyms' =>isset($instance['widget']['settings']['use_synonyms']) ? $instance['widget']['settings']['use_synonyms'] : 0,
  202. '#delimiter' =>isset($instance['widget']['settings']['delimiter']) ? $instance['widget']['settings']['delimiter'] : '',
  203. '#not_found_message' =>isset($instance['widget']['settings']['not_found_message']) ? $instance['widget']['settings']['not_found_message'] : "The term '@term' will be added.",
  204. );
  205. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED ? TRUE : FALSE;
  206. $tags = array();
  207. foreach ($items as $item) {
  208. $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  209. }
  210. $element['#element_validate'] = array('taxonomy_autocomplete_validate');
  211. $element += array(
  212. '#multiple' => $multiple,
  213. '#autocomplete_deluxe_path' => url($instance['widget']['settings']['autocomplete_deluxe_path'] . '/' . $field['field_name'], array('absolute' => TRUE)),
  214. '#default_value' => autocomplete_deluxe_taxonomy_implode_tags($tags),
  215. );
  216. return $element;
  217. }
  218. /**
  219. * Generates the basic form elements and javascript settings.
  220. */
  221. function autocomplete_deluxe_element_process($element) {
  222. $element['#attached'] = array(
  223. 'library' => array(array('system', 'ui.autocomplete'), array('system', 'ui.button')),
  224. 'js' => array(drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.js'),
  225. 'css' => array(drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.css'),
  226. );
  227. // Workaround for problems with jquery css in seven theme.
  228. if ($GLOBALS['theme'] == 'seven') {
  229. $element['#attached']['css'][] = drupal_get_path('module', 'autocomplete_deluxe') . '/autocomplete_deluxe.seven.css';
  230. }
  231. $html_id = drupal_html_id('autocomplete-deluxe-input');
  232. $element['#after_build'][] = 'autocomplete_deluxe_after_build';
  233. // Set default options for multiple values.
  234. $element['#multiple'] = isset($element['#multiple']) ? $element['#multiple'] : FALSE;
  235. $element['textfield'] = array(
  236. '#type' => 'textfield',
  237. '#size' => isset($element['#size']) ? $element['#size'] : '',
  238. '#attributes' => array('class' => array('autocomplete-deluxe-form'), 'id' => array($html_id)),
  239. '#default_value' => '',
  240. '#prefix' => '<div class="autocomplete-deluxe-container">',
  241. '#suffix' => '</div>',
  242. );
  243. $js_settings['autocomplete_deluxe'][$html_id] = array(
  244. 'input_id' => $html_id,
  245. 'multiple' => $element['#multiple'],
  246. 'required' => $element['#required'],
  247. 'limit' => isset($element['#limit']) ? $element['#limit'] : 10,
  248. 'min_length' => isset($element['#min_length']) ? $element['#min_length'] : 0,
  249. 'use_synonyms' => isset($element['#use_synonyms']) ? $element['#use_synonyms'] : 0,
  250. 'delimiter' => isset($element['#delimiter']) ? $element['#delimiter'] : '',
  251. 'not_found_message' => isset($element['#not_found_message']) ? $element['#not_found_message'] : "The term '@term' will be added.",
  252. );
  253. if (isset($element['#autocomplete_deluxe_path'])) {
  254. if (isset($element['#default_value'])) {
  255. // Split on the comma only if that comma has zero, or an even number of
  256. // quotes in ahead of it.
  257. // http://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes
  258. $default_value = preg_replace('/,(?=([^\"]*\"[^\"]*\")*[^\"]*$)/i', '"" ""', $element['#default_value']);
  259. $default_value = '""' . $default_value . '""';
  260. }
  261. else {
  262. $default_value = '';
  263. }
  264. if ($element['#multiple']) {
  265. $element['value_field'] = array(
  266. '#type' => 'textfield',
  267. '#attributes' => array('class' => array('autocomplete-deluxe-value-field')),
  268. '#default_value' => $default_value,
  269. '#prefix' => '<div class="autocomplete-deluxe-value-container">',
  270. '#suffix' => '</div>',
  271. );
  272. $element['textfield']['#attributes']['style'] = array('display:none');
  273. }
  274. else {
  275. $element['textfield']['#default_value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  276. }
  277. $js_settings['autocomplete_deluxe'][$html_id] += array(
  278. 'type' => 'ajax',
  279. 'uri' => $element['#autocomplete_deluxe_path'],
  280. );
  281. }
  282. else {
  283. // If there is no source (path or data), we don't want to add the js
  284. // settings and so the functions will be abborted.
  285. return $element;
  286. }
  287. $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
  288. $element['#tree'] = TRUE;
  289. return $element;
  290. }
  291. /**
  292. * Helper function to determine the value for a autocomplete deluxe form
  293. * element.
  294. */
  295. function autocomplete_deluxe_value(&$element, $input = FALSE, $form_state = NULL) {
  296. // This runs before child elements are processed, so we cannot calculate the
  297. // value here. But we have to make sure the value is an array, so the form
  298. // API is able to proccess the children to set their values in the array. Thus
  299. // once the form API has finished processing the element, the value is an
  300. // array containing the child element values. Then finally the after build
  301. // callback converts it back to the numeric value and sets that.
  302. return array();
  303. }
  304. /**
  305. * FAPI after build callback for the duration parameter type form.
  306. * Fixes up the form value by applying the multiplier.
  307. */
  308. function autocomplete_deluxe_after_build($element, &$form_state) {
  309. // By default drupal sets the maxlength to 128 if the property isn't
  310. // specified, but since the limit isn't useful in some cases,
  311. // we unset the property.
  312. unset($element['textfield']['#maxlength']);
  313. // Set the elements value from either the value field or text field input.
  314. $element['#value'] = isset($element['value_field']) ? $element['value_field']['#value'] : $element['textfield']['#value'];
  315. if (isset($element['value_field'])) {
  316. $element['#value'] = trim($element['#value']);
  317. // Replace all double double quotes and space with a comma. This will allows
  318. // us to keep entries in double quotes.
  319. $element['#value'] = str_replace('"" ""', ',', $element['#value']);
  320. $element['#value'] = str_replace('"" ""', ',', $element['#value']);
  321. // Remove the double quotes at the beginning and the end from the first and
  322. // the last term.
  323. $element['#value'] = substr($element['#value'], 2, strlen($element['#value']) - 4);
  324. unset($element['value_field']['#maxlength']);
  325. }
  326. form_set_value($element, $element['#value'], $form_state);
  327. return $element;
  328. }
  329. /**
  330. * Implements hook_element_info().
  331. */
  332. function autocomplete_deluxe_element_info() {
  333. $types['autocomplete_deluxe'] = array(
  334. '#input' => TRUE,
  335. '#value_callback' => 'autocomplete_deluxe_value',
  336. '#pre_render' => array('form_pre_render_conditional_form_element'),
  337. '#process' => array('autocomplete_deluxe_element_process'),
  338. );
  339. return $types;
  340. }
  341. /**
  342. * Implements hook_menu().
  343. */
  344. function autocomplete_deluxe_menu() {
  345. $items['autocomplete_deluxe/taxonomy'] = array(
  346. 'title' => 'Autocomplete deluxe taxonomy',
  347. 'page callback' => 'autocomplete_deluxe_taxonomy_callback',
  348. 'access arguments' => array('access content'),
  349. 'type' => MENU_CALLBACK,
  350. );
  351. return $items;
  352. }