bootstrap-table-commonsearch.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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, ColumnsForSearch = [];
  10. var sprintf = $.fn.bootstrapTable.utils.sprintf;
  11. var initCommonSearch = function (pColumns, that) {
  12. var vFormCommon = createFormCommon(pColumns, that), timeoutId = 0;
  13. var vModal = sprintf("<div id=\"commonSearchContent_%s\" class=\"common-search-table %s\">", that.options.idTable, that.options.searchFormVisible ? "" : "hidden");
  14. vModal += vFormCommon.join('');
  15. vModal += "</div>";
  16. $("#myTabContent").before($(vModal));
  17. var form = $("#commonSearchForm" + "_" + that.options.idTable);
  18. //绑定日期时间元素事件
  19. if ($(".datetimepicker", form).size() > 0) {
  20. require(['bootstrap-datetimepicker'], function () {
  21. $('.datetimepicker', form).parent().css('position', 'relative');
  22. $('.datetimepicker', form).datetimepicker({
  23. //format: 'YYYY-MM-DD',
  24. icons: {
  25. time: 'fa fa-clock-o',
  26. date: 'fa fa-calendar',
  27. up: 'fa fa-chevron-up',
  28. down: 'fa fa-chevron-down',
  29. previous: 'fa fa-chevron-left',
  30. next: 'fa fa-chevron-right',
  31. today: 'fa fa-history',
  32. clear: 'fa fa-trash',
  33. close: 'fa fa-remove'
  34. },
  35. showTodayButton: true,
  36. showClose: true
  37. });
  38. });
  39. }
  40. // 表单提交
  41. form.on("submit", function (event) {
  42. that.onColumnCommonSearch();
  43. return false;
  44. });
  45. // 重置搜索
  46. form.on("click", "#btnResetCommon" + "_" + that.options.idTable, function (event) {
  47. form[0].reset();
  48. that.onColumnCommonSearch();
  49. });
  50. };
  51. var createFormCommon = function (pColumns, that) {
  52. var htmlForm = [];
  53. var opList = ['=', '>', '>=', '<', '<=', '!=', 'LIKE', 'LIKE %...%', 'NOT LIKE', 'IN(...)', 'NOT IN(...)', 'BETWEEN', 'NOT BETWEEN', 'IS NULL', 'IS NOT NULL'];
  54. htmlForm.push(sprintf('<form class="form-inline" id="commonSearchForm_%s" action="%s" >', that.options.idTable, that.options.actionForm));
  55. htmlForm.push('<fieldset>');
  56. if (that.options.titleForm.length > 0)
  57. htmlForm.push(sprintf("<legend>%s</legend>", that.options.titleForm));
  58. for (var i in pColumns) {
  59. var vObjCol = pColumns[i];
  60. if (!vObjCol.checkbox && vObjCol.field !== 'operate' && vObjCol.searchable && vObjCol.operate !== false) {
  61. var query = Backend.api.query(vObjCol.field);
  62. query = query ? query : '';
  63. vObjCol.defaultValue = that.options.renderDefault && query != '' ? query : (typeof vObjCol.defaultValue === 'undefined' ? '' : vObjCol.defaultValue);
  64. ColumnsForSearch.push(vObjCol);
  65. htmlForm.push('<div class="form-group" style="margin:5px">');
  66. htmlForm.push(sprintf('<label for="%s" class="control-label" style="padding:0 10px">%s</label>', vObjCol.field, vObjCol.title));
  67. //htmlForm.push('<div class="col-sm-2">');
  68. //htmlForm.push(sprintf('<select class="form-control" name="field-%s" data-name="%s">%s</select>', vObjCol.field, vObjCol.field, selectHtml));
  69. vObjCol.operate = (typeof vObjCol.operate === 'undefined' || $.inArray(vObjCol.operate, opList) === -1) ? '=' : vObjCol.operate;
  70. 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));
  71. //htmlForm.push('</div>');
  72. //htmlForm.push('<div class="col-sm-8">');
  73. var style = typeof vObjCol.style === 'undefined' ? '' : sprintf('style="%s"', vObjCol.style);
  74. if (vObjCol.searchList) {
  75. if (typeof vObjCol.searchList == 'function') {
  76. htmlForm.push(vObjCol.searchList.call(this, vObjCol));
  77. } else {
  78. var isArray = vObjCol.searchList.constructor === Array;
  79. var searchList = [];
  80. searchList.push(sprintf('<option value="">%s</option>', that.options.formatCommonChoose()));
  81. $.each(vObjCol.searchList, function (key, value) {
  82. var isSelect = (isArray ? value : key) === vObjCol.defaultValue ? 'selected' : '';
  83. searchList.push(sprintf("<option value='" + (isArray ? value : key) + "' %s>" + value + "</option>", isSelect));
  84. });
  85. htmlForm.push(sprintf('<select class="form-control" name="%s" %s>%s</select>', vObjCol.field, style, searchList.join('')));
  86. }
  87. } else {
  88. var placeholder = typeof vObjCol.placeholder === 'undefined' ? vObjCol.title : vObjCol.placeholder;
  89. var type = typeof vObjCol.type === 'undefined' ? 'text' : vObjCol.type;
  90. var addclass = typeof vObjCol.addclass === 'undefined' ? 'form-control' : 'form-control ' + vObjCol.addclass;
  91. var data = typeof vObjCol.data === 'undefined' ? '' : vObjCol.data;
  92. var defaultValue = typeof vObjCol.defaultValue === 'undefined' ? '' : vObjCol.defaultValue;
  93. if (/BETWEEN$/.test(vObjCol.operate)) {
  94. var defaultValueArr = /^.+|.+$/.test(defaultValue) ? defaultValue.split('|') : ['', ''];
  95. htmlForm.push(sprintf('<input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s" %s %s>', type, addclass, vObjCol.field, defaultValueArr[0], placeholder, vObjCol.field, style, data));
  96. htmlForm.push(sprintf('&nbsp;-&nbsp;<input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s" %s %s>', type, addclass, vObjCol.field, defaultValueArr[1], placeholder, vObjCol.field, style, data));
  97. } else {
  98. htmlForm.push(sprintf('<input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s" %s %s>', type, addclass, vObjCol.field, defaultValue, placeholder, vObjCol.field, style, data));
  99. }
  100. }
  101. //htmlForm.push('</div>');
  102. htmlForm.push('</div>');
  103. }
  104. }
  105. htmlForm.push(createFormBtn(that).join(''));
  106. htmlForm.push('</fieldset>');
  107. htmlForm.push('</form>');
  108. return htmlForm;
  109. };
  110. var createFormBtn = function (that) {
  111. var htmlBtn = [];
  112. var searchSubmit = that.options.formatCommonSubmitButton();
  113. var searchReset = that.options.formatCommonResetButton();
  114. htmlBtn.push('<div class="form-group" style="margin:5px">');
  115. htmlBtn.push('<div class="col-sm-12 text-center">');
  116. htmlBtn.push(sprintf('<button type="submit" id="btnSubmitCommon%s" class="btn btn-success" >%s</button> ', "_" + that.options.idTable, searchSubmit));
  117. htmlBtn.push(sprintf('<button type="button" id="btnResetCommon%s" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchReset));
  118. htmlBtn.push('</div>');
  119. htmlBtn.push('</div>');
  120. return htmlBtn;
  121. };
  122. var isSearchAvailble = function (that) {
  123. //只支持服务端搜索
  124. if (!that.options.commonSearch || that.options.sidePagination != 'server' || !that.options.url) {
  125. return false;
  126. }
  127. if (!that.options.idTable) {
  128. return false;
  129. }
  130. return true;
  131. };
  132. var getSearchQuery = function (that) {
  133. var op = {};
  134. var filter = {};
  135. $("#commonSearchContent_" + that.options.idTable + " input.operate").each(function (i) {
  136. var name = $(this).data("name");
  137. var sym = $(this).val();
  138. var obj = $("[name='" + name + "']");
  139. if (obj.size() == 0)
  140. return true;
  141. var vObjCol = ColumnsForSearch[i];
  142. if (obj.size() > 1) {
  143. if (/BETWEEN$/.test(sym)) {
  144. var value_begin = $.trim($("[name='" + name + "']:first").val()), value_end = $.trim($("[name='" + name + "']:last").val());
  145. if (!value_begin.length || !value_end.length) {
  146. return true;
  147. }
  148. if (typeof vObjCol.process === 'function') {
  149. value_begin = vObjCol.process(value_begin, 'begin');
  150. value_end = vObjCol.process(value_end, 'end');
  151. } else if ($("[name='" + name + "']:first").attr('type') === 'datetime') { //datetime类型字段转换成时间戳
  152. var Hms = Moment(value_begin).format("HH:mm:ss");
  153. value_begin = parseInt(Moment(value_begin) / 1000);
  154. value_end = parseInt(Moment(value_end) / 1000);
  155. if (value_begin === value_end && '00:00:00' === Hms) {
  156. value_end += 86399;
  157. }
  158. }
  159. var value = value_begin + ',' + value_end;
  160. } else {
  161. var value = $("[name='" + name + "']:checked").val();
  162. }
  163. } else {
  164. var value = (typeof vObjCol.process === 'function') ? vObjCol.process(obj.val()) : obj.val();
  165. }
  166. if (value == '' && sym.indexOf("NULL") == -1) {
  167. return true;
  168. }
  169. op[name] = sym;
  170. filter[name] = value;
  171. });
  172. return {op: op, filter: filter};
  173. };
  174. $.extend($.fn.bootstrapTable.defaults, {
  175. commonSearch: false,
  176. titleForm: "Common search",
  177. actionForm: "",
  178. idTable: undefined,
  179. searchFormVisible: true,
  180. searchClass: 'searchit',
  181. renderDefault: true,
  182. onColumnCommonSearch: function (field, text) {
  183. return false;
  184. }
  185. });
  186. $.extend($.fn.bootstrapTable.defaults.icons, {
  187. commonSearchIcon: 'glyphicon-search'
  188. });
  189. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  190. 'column-common-search.bs.table': 'onColumnCommonSearch'
  191. });
  192. $.extend($.fn.bootstrapTable.locales[$.fn.bootstrapTable.defaults.locale], {
  193. formatCommonSearch: function () {
  194. return "Common search";
  195. },
  196. formatCommonSubmitButton: function () {
  197. return "Submit";
  198. },
  199. formatCommonResetButton: function () {
  200. return "Reset";
  201. },
  202. formatCommonCloseButton: function () {
  203. return "Close";
  204. },
  205. formatCommonChoose: function () {
  206. return "Choose";
  207. }
  208. });
  209. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
  210. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  211. _initToolbar = BootstrapTable.prototype.initToolbar,
  212. _load = BootstrapTable.prototype.load,
  213. _initSearch = BootstrapTable.prototype.initSearch;
  214. BootstrapTable.prototype.initToolbar = function () {
  215. _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
  216. if (!isSearchAvailble(this)) {
  217. return;
  218. }
  219. var that = this,
  220. html = [];
  221. html.push(sprintf('<div class="columns-%s pull-%s" style="margin-top:10px;">', this.options.buttonsAlign, this.options.buttonsAlign));
  222. html.push(sprintf('<button class="btn btn-default%s' + '" type="button" name="commonSearch" title="%s">', that.options.iconSize === undefined ? '' : ' btn-' + that.options.iconSize, that.options.formatCommonSearch()));
  223. html.push(sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.commonSearchIcon))
  224. html.push('</button></div>');
  225. that.$toolbar.prepend(html.join(''));
  226. initCommonSearch(that.columns, that);
  227. var searchContainer = $("#commonSearchContent_" + that.options.idTable);
  228. that.$toolbar.find('button[name="commonSearch"]')
  229. .off('click').on('click', function () {
  230. searchContainer.toggleClass("hidden");
  231. return;
  232. });
  233. that.$container.on("click", "." + that.options.searchClass, function () {
  234. var obj = $("form [name='" + $(this).data("field") + "']", searchContainer);
  235. if (obj.size() > 0) {
  236. obj.val($(this).data("value"));
  237. $("form", searchContainer).trigger("submit");
  238. }
  239. });
  240. var searchquery = getSearchQuery(this);
  241. this.options.queryParams = function (params) {
  242. return {
  243. search: params.search,
  244. sort: params.sort,
  245. order: params.order,
  246. filter: JSON.stringify(searchquery.filter),
  247. op: JSON.stringify(searchquery.op),
  248. offset: params.offset,
  249. limit: params.limit,
  250. };
  251. };
  252. };
  253. BootstrapTable.prototype.load = function (data) {
  254. _load.apply(this, Array.prototype.slice.apply(arguments));
  255. if (!isSearchAvailble(this)) {
  256. return;
  257. }
  258. if (!firstLoad) {
  259. var height = parseInt($(".bootstrap-table").height());
  260. height += 10;
  261. $("#" + this.options.idTable).bootstrapTable("resetView", {height: height});
  262. firstLoad = true;
  263. }
  264. };
  265. BootstrapTable.prototype.initSearch = function () {
  266. _initSearch.apply(this, Array.prototype.slice.apply(arguments));
  267. if (!isSearchAvailble(this)) {
  268. return;
  269. }
  270. var that = this;
  271. var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
  272. this.data = fp ? $.grep(this.data, function (item, i) {
  273. for (var key in fp) {
  274. var fval = fp[key].toLowerCase();
  275. var value = item[key];
  276. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
  277. that.header.formatters[$.inArray(key, that.header.fields)],
  278. [value, item, i], value);
  279. if (!($.inArray(key, that.header.fields) !== -1 &&
  280. (typeof value === 'string' || typeof value === 'number') &&
  281. (value + '').toLowerCase().indexOf(fval) !== -1)) {
  282. return false;
  283. }
  284. }
  285. return true;
  286. }) : this.data;
  287. };
  288. BootstrapTable.prototype.onColumnCommonSearch = function (event) {
  289. if (typeof event === 'undefined') {
  290. var searchquery = getSearchQuery(this);
  291. // 追加查询关键字
  292. this.options.pageNumber = 1;
  293. this.options.queryParams = function (params) {
  294. return {
  295. search: params.search,
  296. sort: params.sort,
  297. order: params.order,
  298. filter: JSON.stringify(searchquery.filter),
  299. op: JSON.stringify(searchquery.op),
  300. offset: params.offset,
  301. limit: params.limit,
  302. };
  303. };
  304. this.refresh({query: {filter: JSON.stringify(searchquery.filter), op: JSON.stringify(searchquery.op)}});
  305. } else {
  306. var text = $.trim($(event.currentTarget).val());
  307. var $field = $(event.currentTarget)[0].id;
  308. if ($.isEmptyObject(this.filterColumnsPartial)) {
  309. this.filterColumnsPartial = {};
  310. }
  311. if (text) {
  312. this.filterColumnsPartial[$field] = text;
  313. } else {
  314. delete this.filterColumnsPartial[$field];
  315. }
  316. this.options.pageNumber = 1;
  317. this.onSearch(event);
  318. // this.updatePagination();
  319. this.trigger('column-common-search', $field, text);
  320. }
  321. };
  322. }(jQuery);