bootstrap-table-commonsearch.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /**
  2. * @author: pppscn <35696959@qq.com>
  3. * @version: v0.0.1
  4. *
  5. * @update 2017-05-07 <http://git.oschina.net/pp/fastadmin>
  6. */
  7. !function ($) {
  8. 'use strict';
  9. var firstLoad = false;
  10. var sprintf = $.fn.bootstrapTable.utils.sprintf;
  11. var showCommonSearch = function (pColumns, that) {
  12. var vFormCommon = createFormCommon(pColumns, that), timeoutId = 0;
  13. var vModal = sprintf("<div id=\"commonSearchModalContent_%s\" class=\"well bs-component\">", that.options.idTable);
  14. vModal += vFormCommon.join('');
  15. vModal += "</div>";
  16. $("#myTabContent").before($(vModal));
  17. if (that.options.sidePagination != 'server' || !that.options.url) {
  18. $('#' + that.options.idForm).off('keyup blur', 'input').on('keyup blur', 'input', function (event) {
  19. clearTimeout(timeoutId);
  20. timeoutId = setTimeout(function () {
  21. that.onColumnCommonSearch(event);
  22. }, that.options.searchTimeOut);
  23. });
  24. }
  25. //绑定日期时间元素事件
  26. var form = $("#" + that.options.idForm);
  27. if ($(".datetimepicker", form).size() > 0) {
  28. require(['bootstrap-datetimepicker'], function () {
  29. $('.datetimepicker', form).parent().css('position', 'relative');
  30. $('.datetimepicker', form).datetimepicker({
  31. //format: 'YYYY-MM-DD',
  32. icons: {
  33. time: 'fa fa-clock-o',
  34. date: 'fa fa-calendar',
  35. up: 'fa fa-chevron-up',
  36. down: 'fa fa-chevron-down',
  37. previous: 'fa fa-chevron-left',
  38. next: 'fa fa-chevron-right',
  39. today: 'fa fa-history',
  40. clear: 'fa fa-trash',
  41. close: 'fa fa-remove'
  42. },
  43. showTodayButton: true,
  44. showClose: true
  45. });
  46. });
  47. }
  48. // 提交搜索
  49. $("#btnSubmitCommon" + "_" + that.options.idTable).click(function (event) {
  50. that.onColumnCommonSearch();
  51. });
  52. // 重置搜索
  53. $("#btnResetCommon" + "_" + that.options.idTable).click(function () {
  54. $("#commonSearchModalContent" + "_" + that.options.idTable + " form")[0].reset();
  55. that.onColumnCommonSearch();
  56. });
  57. };
  58. var createFormCommon = function (pColumns, that) {
  59. var htmlForm = [];
  60. var opList = ['=', '>', '>=', '<', '<=', '!=', 'LIKE', 'LIKE %...%', 'NOT LIKE', 'IN(...)', 'NOT IN(...)', 'BETWEEN', 'NOT BETWEEN', 'IS NULL', 'IS NOT NULL'];
  61. //var selectList = [];
  62. //for (var i = 0; i < opList.length; i++) {
  63. // selectList.push("<option value='" + opList[i] + "'>" + opList[i] + "</option>");
  64. //}
  65. //var selectHtml = selectList.join('');
  66. htmlForm.push(sprintf('<form class="form-inline" id="%s" action="%s" >', that.options.idForm, that.options.actionForm));
  67. htmlForm.push('<fieldset>');
  68. if (that.options.titleForm.length > 0)
  69. htmlForm.push(sprintf("<legend>%s</legend>", that.options.titleForm));
  70. for (var i in pColumns) {
  71. var vObjCol = pColumns[i];
  72. if (!vObjCol.checkbox && vObjCol.field !== 'operate' && vObjCol.visible && vObjCol.searchable && vObjCol.operate !== false) {
  73. htmlForm.push('<div class="form-group" style="margin:0 5px;">');
  74. htmlForm.push(sprintf('<label for="%s" class="control-label" style="padding:0 10px">%s</label>', vObjCol.field, vObjCol.title));
  75. if (that.options.sidePagination == 'server' && that.options.url) {
  76. //htmlForm.push('<div class="col-sm-2">');
  77. //htmlForm.push(sprintf('<select class="form-control" name="field-%s" data-name="%s">%s</select>', vObjCol.field, vObjCol.field, selectHtml));
  78. vObjCol.operate = (typeof vObjCol.operate === 'undefined' || $.inArray(vObjCol.operate, opList) === -1) ? '=' : vObjCol.operate;
  79. htmlForm.push(sprintf('<input type="hidden" class="form-control operate" name="field-%s" data-name="%s" value="%s" readonly>', vObjCol.field, vObjCol.field, vObjCol.operate));
  80. //htmlForm.push('</div>');
  81. }
  82. //htmlForm.push('<div class="col-sm-8">');
  83. var style = typeof vObjCol.style === 'undefined' ? '' : sprintf('style="%s"', vObjCol.style);
  84. if (vObjCol.searchList) {
  85. if (typeof vObjCol.searchList == 'function') {
  86. htmlForm.push(vObjCol.searchList.call(this, vObjCol));
  87. } else {
  88. var isArray = vObjCol.searchList.constructor === Array;
  89. var searchList = [];
  90. searchList.push(sprintf('<option value="">%s</option>', $.fn.bootstrapTable.locales.formatCommonChoose()));
  91. $.each(vObjCol.searchList, function (key, value) {
  92. searchList.push("<option value='" + (isArray ? value : key) + "'>" + value + "</option>");
  93. });
  94. htmlForm.push(sprintf('<select class="form-control" name="%s" %s>%s</select>', vObjCol.field, style, searchList.join('')));
  95. }
  96. } else {
  97. var placeholder = typeof vObjCol.placeholder === 'undefined' ? vObjCol.title : vObjCol.placeholder;
  98. var type = typeof vObjCol.type === 'undefined' ? 'text' : vObjCol.type;
  99. var addclass = typeof vObjCol.addclass === 'undefined' ? 'form-control' : 'form-control ' + vObjCol.addclass;
  100. var data = typeof vObjCol.data === 'undefined' ? '' : vObjCol.data;
  101. htmlForm.push(sprintf('<input type="%s" class="%s" name="%s" placeholder="%s" id="%s" %s %s>', type, addclass, vObjCol.field, placeholder, vObjCol.field, style, data));
  102. var reg = /BETWEEN$/;
  103. if (reg.test(vObjCol.operate)) {
  104. htmlForm.push(sprintf('&nbsp;-&nbsp;<input type="%s" class="%s" name="%s" placeholder="%s" id="%s" %s %s>', type, addclass, vObjCol.field, placeholder, vObjCol.field, style, data));
  105. }
  106. }
  107. //htmlForm.push('</div>');
  108. htmlForm.push('</div>');
  109. }
  110. }
  111. htmlForm.push('<div class="form-group" style="margin:0 5px;">');
  112. htmlForm.push(createFormBtn(that).join(''));
  113. htmlForm.push('</div>');
  114. htmlForm.push('</fieldset>');
  115. htmlForm.push('</form>');
  116. return htmlForm;
  117. };
  118. var createFormBtn = function (that) {
  119. var htmlBtn = [];
  120. var searchSubmit = that.options.formatCommonSubmitButton();
  121. var searchReset = that.options.formatCommonResetButton();
  122. var searchClose = that.options.formatCommonCloseButton();
  123. htmlBtn.push('<div class="form-group">');
  124. htmlBtn.push('<div class="col-sm-12 text-center">');
  125. if (that.options.sidePagination == 'server' && that.options.url) {
  126. htmlBtn.push(sprintf('<button type="button" id="btnSubmitCommon%s" class="btn btn-success" >%s</button> ', "_" + that.options.idTable, searchSubmit));
  127. htmlBtn.push(sprintf('<button type="button" id="btnResetCommon%s" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchReset));
  128. } else {
  129. htmlBtn.push(sprintf('<button type="button" id="btnCloseCommon%s" data-dismiss="modal" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchClose));
  130. }
  131. htmlBtn.push('</div>');
  132. htmlBtn.push('</div>');
  133. return htmlBtn;
  134. };
  135. $.extend($.fn.bootstrapTable.defaults, {
  136. commonSearch: false,
  137. idForm: 'commonSearch',
  138. titleForm: __("Common search"),
  139. actionForm: '',
  140. idTable: undefined,
  141. onColumnCommonSearch: function (field, text) {
  142. return false;
  143. }
  144. });
  145. $.extend($.fn.bootstrapTable.defaults.icons, {
  146. commonSearchIcon: 'glyphicon-search'
  147. });
  148. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  149. 'column-common-search.bs.table': 'onColumnCommonSearch'
  150. });
  151. $.extend($.fn.bootstrapTable.locales, {
  152. formatCommonSearch: function () {
  153. return __("Common search");
  154. },
  155. formatCommonSubmitButton: function () {
  156. return __("Submit");
  157. },
  158. formatCommonResetButton: function () {
  159. return __("Reset");
  160. },
  161. formatCommonCloseButton: function () {
  162. return __("Close");
  163. },
  164. formatCommonChoose: function () {
  165. return __("Choose");
  166. }
  167. });
  168. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
  169. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  170. _initToolbar = BootstrapTable.prototype.initToolbar,
  171. _load = BootstrapTable.prototype.load,
  172. _initSearch = BootstrapTable.prototype.initSearch;
  173. BootstrapTable.prototype.initToolbar = function () {
  174. _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
  175. if (!this.options.search) {
  176. return;
  177. }
  178. if (!this.options.commonSearch) {
  179. return;
  180. }
  181. if (!this.options.idTable) {
  182. return;
  183. }
  184. var that = this;
  185. showCommonSearch(that.columns, that);
  186. };
  187. BootstrapTable.prototype.load = function (data) {
  188. _load.apply(this, Array.prototype.slice.apply(arguments));
  189. if (!this.options.commonSearch) {
  190. return;
  191. }
  192. if (typeof this.options.idTable === 'undefined') {
  193. return;
  194. } else {
  195. if (!firstLoad) {
  196. var height = parseInt($(".bootstrap-table").height());
  197. height += 10;
  198. $("#" + this.options.idTable).bootstrapTable("resetView", {height: height});
  199. firstLoad = true;
  200. }
  201. }
  202. };
  203. BootstrapTable.prototype.initSearch = function () {
  204. _initSearch.apply(this, Array.prototype.slice.apply(arguments));
  205. if (!this.options.commonSearch) {
  206. return;
  207. }
  208. var that = this;
  209. var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
  210. this.data = fp ? $.grep(this.data, function (item, i) {
  211. for (var key in fp) {
  212. var fval = fp[key].toLowerCase();
  213. var value = item[key];
  214. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
  215. that.header.formatters[$.inArray(key, that.header.fields)],
  216. [value, item, i], value);
  217. if (!($.inArray(key, that.header.fields) !== -1 &&
  218. (typeof value === 'string' || typeof value === 'number') &&
  219. (value + '').toLowerCase().indexOf(fval) !== -1)) {
  220. return false;
  221. }
  222. }
  223. return true;
  224. }) : this.data;
  225. };
  226. BootstrapTable.prototype.onColumnCommonSearch = function (event) {
  227. if (typeof event === 'undefined') {
  228. var op = {};
  229. var filter = {};
  230. $("#commonSearchModalContent_" + this.options.idTable + " input.operate").each(function () {
  231. var name = $(this).data("name");
  232. var sym = $(this).val();
  233. var obj = $("[name='" + name + "']");
  234. if (obj.size() == 0)
  235. return true;
  236. if (obj.size() > 1) {
  237. if (/BETWEEN$/.test(sym)) {
  238. var value_begin = $.trim($("[name='" + name + "']:first").val()), value_end = $.trim($("[name='" + name + "']:last").val());
  239. if (!value_begin.length || !value_end.length) {
  240. return true;
  241. }
  242. //datetime类型字段转换成时间戳
  243. if ($("[name='" + name + "']:first").attr('type') === 'datetime') {
  244. var datetimestamp = Date.parse(value_begin).toString();
  245. value_begin = datetimestamp.substr(0, datetimestamp.length - 3) - 28800; //TODO:Date.parse导致的时区差
  246. datetimestamp = Date.parse(value_end).toString();
  247. value_end = datetimestamp.substr(0, datetimestamp.length - 3) - 28800; //TODO:Date.parse导致的时区差
  248. }
  249. var value = value_begin + ',' + value_end;
  250. } else {
  251. var value = $("[name='" + name + "']:checked").val();
  252. }
  253. } else {
  254. var value = obj.val();
  255. }
  256. if (value == '' && sym.indexOf("NULL") == -1) {
  257. return true;
  258. }
  259. op[name] = sym;
  260. filter[name] = value;
  261. });
  262. // 追加查询关键字
  263. this.options.pageNumber = 1;
  264. this.options.queryParams = function (params) {
  265. return {
  266. search: params.search,
  267. sort: params.sort,
  268. order: params.order,
  269. filter: JSON.stringify(filter),
  270. op: JSON.stringify(op),
  271. offset: params.offset,
  272. limit: params.limit,
  273. };
  274. };
  275. this.refresh({query: {filter: JSON.stringify(filter), op: JSON.stringify(op)}});
  276. } else {
  277. var text = $.trim($(event.currentTarget).val());
  278. var $field = $(event.currentTarget)[0].id;
  279. if ($.isEmptyObject(this.filterColumnsPartial)) {
  280. this.filterColumnsPartial = {};
  281. }
  282. if (text) {
  283. this.filterColumnsPartial[$field] = text;
  284. } else {
  285. delete this.filterColumnsPartial[$field];
  286. }
  287. this.options.pageNumber = 1;
  288. this.onSearch(event);
  289. // this.updatePagination();
  290. this.trigger('column-common-search', $field, text);
  291. }
  292. };
  293. }(jQuery);