select_ajax.php 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * A drop down list with all languages to use with QuickForm
  5. */
  6. class HTML_QuickForm_Select_Ajax extends HTML_QuickForm_select
  7. {
  8. /**
  9. * Class constructor
  10. */
  11. function HTML_QuickForm_Select_Ajax($elementName = null, $elementLabel = null, $options = null, $attributes = null)
  12. {
  13. parent::HTML_QuickForm_Select($elementName, $elementLabel, $options, $attributes);
  14. }
  15. /**
  16. * The ajax call must contain an array of id and text
  17. * @return string
  18. */
  19. function toHtml()
  20. {
  21. //$html = api_get_js('select2/select2.js');
  22. $html = null;
  23. /*$iso = api_get_language_isocode(api_get_interface_language());
  24. $localeFile = 'select2_locale_'.$iso.'.js';
  25. if (file_exists(api_get_path(LIBRARY_PATH).'javascript/select2/'.$localeFile)) {
  26. $html .= api_get_js('select2/'.$localeFile);
  27. }
  28. $html .= api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/select2/select2.css');*/
  29. $formatResult = $this->getAttribute('formatResult');
  30. $formatCondition = null;
  31. if (!empty($formatResult)) {
  32. $formatCondition = ',
  33. formatResult : '.$formatResult.',
  34. formatSelection : '.$formatResult.',';
  35. }
  36. $defaultValues = $this->getAttribute('defaults');
  37. $dataCondition = null;
  38. $tags = null;
  39. if (!empty($defaultValues)) {
  40. $result = json_encode($defaultValues);
  41. $result = str_replace('"id"', 'id', $result);
  42. $result = str_replace('"text"', 'text', $result);
  43. $dataCondition = '$("#'.$this->getAttribute('name').'").select2("data", '.$result.')';
  44. $tags = ', tags : function() { return '.$result.'} ';
  45. }
  46. $html .= '<script>
  47. $(function() {
  48. $("#'.$this->getAttribute('name').'").select2({
  49. placeholder: "'.get_lang('SelectAnOption').'",
  50. allowClear: true,
  51. width: "element",
  52. minimumInputLength: 2,
  53. // instead of writing the function to execute the request we use Select2s convenient helper
  54. ajax: {
  55. url: "'.$this->getAttribute('url').'",
  56. dataType: "json",
  57. data: function (term, page) {
  58. return {
  59. q: term, // search term
  60. page_limit: 10,
  61. };
  62. },
  63. results: function (data, page) { // parse the results into the format expected by Select2.
  64. // since we are using custom formatting functions we do not need to alter remote JSON data
  65. return {
  66. results: data
  67. };
  68. }
  69. }
  70. '.$tags.'
  71. '.$formatCondition.'
  72. });
  73. '.$dataCondition.'
  74. });
  75. </script>';
  76. $html .= '<input id="'.$this->getAttribute('name').'" name="'.$this->getAttribute('name').'" />';
  77. return $html;
  78. }
  79. }