bootstrap-table-commonsearch.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /**
  2. * FastAdmin通用搜索
  3. *
  4. * @author: pppscn <35696959@qq.com>
  5. * @update 2017-05-07 <https://gitee.com/pp/fastadmin>
  6. *
  7. * @author: Karson <karson@fastadmin.net>
  8. * @update 2018-04-05 <https://gitee.com/karson/fastadmin>
  9. */
  10. !function ($) {
  11. 'use strict';
  12. var ColumnsForSearch = [];
  13. var sprintf = $.fn.bootstrapTable.utils.sprintf;
  14. var initCommonSearch = function (pColumns, that) {
  15. var vFormCommon = createFormCommon(pColumns, that);
  16. var vModal = sprintf("<div class=\"commonsearch-table %s\">", that.options.searchFormVisible ? "" : "hidden");
  17. vModal += vFormCommon;
  18. vModal += "</div>";
  19. that.$container.prepend($(vModal));
  20. that.$commonsearch = $(".commonsearch-table", that.$container);
  21. var form = $("form.form-commonsearch", that.$commonsearch);
  22. require(['form'], function (Form) {
  23. Form.api.bindevent(form);
  24. form.validator("destroy");
  25. });
  26. // 表单提交
  27. form.on("submit", function (event) {
  28. event.preventDefault();
  29. that.onCommonSearch();
  30. return false;
  31. });
  32. // 重置搜索
  33. form.on("click", "button[type=reset]", function (event) {
  34. form[0].reset();
  35. setTimeout(function () {
  36. that.onCommonSearch();
  37. }, 0);
  38. });
  39. };
  40. var createFormCommon = function (pColumns, that) {
  41. // 如果有使用模板则直接返回模板的内容
  42. if (that.options.searchFormTemplate) {
  43. return Template(that.options.searchFormTemplate, {columns: pColumns, table: that});
  44. }
  45. var htmlForm = [];
  46. htmlForm.push(sprintf('<form class="form-horizontal form-commonsearch" novalidate method="post" action="%s" >', that.options.actionForm));
  47. htmlForm.push('<fieldset>');
  48. if (that.options.titleForm.length > 0)
  49. htmlForm.push(sprintf("<legend>%s</legend>", that.options.titleForm));
  50. htmlForm.push('<div class="row">');
  51. for (var i in pColumns) {
  52. var vObjCol = pColumns[i];
  53. if (!vObjCol.checkbox && vObjCol.field !== 'operate' && vObjCol.searchable && vObjCol.operate !== false) {
  54. var query = Fast.api.query(vObjCol.field);
  55. var operate = Fast.api.query(vObjCol.field + "-operate");
  56. var renderDefault = that.options.renderDefault && (typeof vObjCol.renderDefault == 'undefined' || vObjCol.renderDefault);
  57. vObjCol.defaultValue = renderDefault && query ? query : (typeof vObjCol.defaultValue === 'undefined' ? '' : vObjCol.defaultValue);
  58. vObjCol.operate = renderDefault && operate ? operate : (typeof vObjCol.operate === 'undefined' ? '=' : vObjCol.operate);
  59. ColumnsForSearch.push(vObjCol);
  60. htmlForm.push('<div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">');
  61. htmlForm.push(sprintf('<label for="%s" class="control-label col-xs-4">%s</label>', vObjCol.field, vObjCol.title));
  62. htmlForm.push('<div class="col-xs-8">');
  63. vObjCol.operate = vObjCol.operate ? vObjCol.operate.toUpperCase() : '=';
  64. htmlForm.push(sprintf('<input type="hidden" class="form-control operate" name="%s-operate" data-name="%s" value="%s" readonly>', vObjCol.field, vObjCol.field, vObjCol.operate));
  65. var addClass = typeof vObjCol.addClass === 'undefined' ? (typeof vObjCol.addclass === 'undefined' ? 'form-control' : 'form-control ' + vObjCol.addclass) : 'form-control ' + vObjCol.addClass;
  66. var extend = typeof vObjCol.extend === 'undefined' ? '' : vObjCol.extend;
  67. var style = typeof vObjCol.style === 'undefined' ? '' : sprintf('style="%s"', vObjCol.style);
  68. extend = typeof vObjCol.data !== 'undefined' && extend == '' ? vObjCol.data : extend;
  69. extend = typeof vObjCol.autocomplete !== 'undefined' ? extend + ' autocomplete="' + (vObjCol.autocomplete === false || vObjCol.autocomplete === 'off' ? 'off' : 'on') + '"' : extend;
  70. if (vObjCol.searchList) {
  71. if (typeof vObjCol.searchList === 'function') {
  72. htmlForm.push(vObjCol.searchList.call(this, vObjCol));
  73. } else {
  74. var optionList = [sprintf('<option value="">%s</option>', that.options.formatCommonChoose())];
  75. if (typeof vObjCol.searchList === 'object' && typeof vObjCol.searchList.then === 'function') {
  76. (function (vObjCol, that) {
  77. $.when(vObjCol.searchList).done(function (ret) {
  78. var searchList = [];
  79. if (ret.data && ret.data.searchlist && $.isArray(ret.data.searchlist)) {
  80. searchList = ret.data.searchlist;
  81. } else if (ret.constructor === Array || ret.constructor === Object) {
  82. searchList = ret;
  83. }
  84. var optionList = createOptionList(searchList, vObjCol, that);
  85. $("form.form-commonsearch select[name='" + vObjCol.field + "']", that.$container).html(optionList.join('')).trigger("change");
  86. });
  87. })(vObjCol, that);
  88. } else {
  89. optionList = createOptionList(vObjCol.searchList, vObjCol, that);
  90. }
  91. htmlForm.push(sprintf('<select class="%s" name="%s" %s %s>%s</select>', addClass, vObjCol.field, style, extend, optionList.join('')));
  92. }
  93. } else {
  94. var placeholder = typeof vObjCol.placeholder === 'undefined' ? vObjCol.title : vObjCol.placeholder;
  95. var type = typeof vObjCol.type === 'undefined' ? 'text' : vObjCol.type;
  96. var defaultValue = typeof vObjCol.defaultValue === 'undefined' ? '' : vObjCol.defaultValue;
  97. if (/BETWEEN$/.test(vObjCol.operate)) {
  98. var defaultValueArr = defaultValue.toString().match(/\|/) ? defaultValue.split('|') : ['', ''];
  99. var placeholderArr = placeholder.toString().match(/\|/) ? placeholder.split('|') : [placeholder, placeholder];
  100. htmlForm.push('<div class="row row-between">');
  101. htmlForm.push(sprintf('<div class="col-xs-6"><input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s-min" data-index="%s" %s %s></div>', type, addClass, vObjCol.field, defaultValueArr[0], placeholderArr[0], vObjCol.field, i, style, extend));
  102. htmlForm.push(sprintf('<div class="col-xs-6"><input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s-max" data-index="%s" %s %s></div>', type, addClass, vObjCol.field, defaultValueArr[1], placeholderArr[1], vObjCol.field, i, style, extend));
  103. htmlForm.push('</div>');
  104. } else {
  105. htmlForm.push(sprintf('<input type="%s" class="%s" name="%s" value="%s" placeholder="%s" id="%s" data-index="%s" %s %s>', type, addClass, vObjCol.field, defaultValue, placeholder, vObjCol.field, i, style, extend));
  106. }
  107. }
  108. htmlForm.push('</div>');
  109. htmlForm.push('</div>');
  110. }
  111. }
  112. htmlForm.push('<div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">');
  113. htmlForm.push(createFormBtn(that).join(''));
  114. htmlForm.push('</div>');
  115. htmlForm.push('</div>');
  116. htmlForm.push('</fieldset>');
  117. htmlForm.push('</form>');
  118. return htmlForm.join('');
  119. };
  120. var createFormBtn = function (that) {
  121. var htmlBtn = [];
  122. var searchSubmit = that.options.formatCommonSubmitButton();
  123. var searchReset = that.options.formatCommonResetButton();
  124. htmlBtn.push('<div class="col-sm-8 col-xs-offset-4">');
  125. htmlBtn.push(sprintf('<button type="submit" class="btn btn-success" formnovalidate>%s</button> ', searchSubmit));
  126. htmlBtn.push(sprintf('<button type="reset" class="btn btn-default" >%s</button> ', searchReset));
  127. htmlBtn.push('</div>');
  128. return htmlBtn;
  129. };
  130. var createOptionList = function (searchList, vObjCol, that) {
  131. var isArray = searchList.constructor === Array;
  132. var optionList = [];
  133. optionList.push(sprintf('<option value="">%s</option>', that.options.formatCommonChoose()));
  134. $.each(searchList, function (key, value) {
  135. if (value.constructor === Object) {
  136. key = value.id;
  137. value = value.name;
  138. } else {
  139. key = isArray ? value : key;
  140. }
  141. optionList.push(sprintf("<option value='" + key + "' %s>" + value + "</option>", key == vObjCol.defaultValue ? 'selected' : ''));
  142. });
  143. return optionList;
  144. };
  145. var isSearchAvailble = function (that) {
  146. //只支持服务端搜索
  147. if (!that.options.commonSearch || that.options.sidePagination != 'server' || !that.options.url) {
  148. return false;
  149. }
  150. return true;
  151. };
  152. var getSearchQuery = function (that, removeempty) {
  153. var op = {};
  154. var filter = {};
  155. var value = '';
  156. $("form.form-commonsearch .operate", that.$commonsearch).each(function (i) {
  157. var name = $(this).data("name");
  158. var sym = $(this).is("select") ? $("option:selected", this).val() : $(this).val().toUpperCase();
  159. var obj = $("[name='" + name + "']", that.$commonsearch);
  160. if (obj.size() == 0)
  161. return true;
  162. var vObjCol = ColumnsForSearch[i];
  163. var process = !that.options.searchFormTemplate && vObjCol && typeof vObjCol.process == 'function' ? vObjCol.process : null;
  164. if (obj.size() > 1) {
  165. if (/BETWEEN$/.test(sym)) {
  166. var value_begin = $.trim($("[name='" + name + "']:first", that.$commonsearch).val()),
  167. value_end = $.trim($("[name='" + name + "']:last", that.$commonsearch).val());
  168. if (value_begin.length || value_end.length) {
  169. if (process) {
  170. value_begin = process(value_begin, 'begin');
  171. value_end = process(value_end, 'end');
  172. }
  173. value = value_begin + ',' + value_end;
  174. } else {
  175. value = '';
  176. }
  177. //如果是时间筛选,将operate置为RANGE
  178. if ($("[name='" + name + "']:first", that.$commonsearch).hasClass("datetimepicker")) {
  179. sym = 'RANGE';
  180. }
  181. } else {
  182. value = $("[name='" + name + "']:checked", that.$commonsearch).val();
  183. value = process ? process(value) : value;
  184. }
  185. } else {
  186. value = process ? process(obj.val()) : obj.val();
  187. }
  188. if (removeempty && (value == '' || value == null || ($.isArray(value) && value.length == 0)) && !sym.match(/null/i)) {
  189. return true;
  190. }
  191. op[name] = sym;
  192. filter[name] = value;
  193. });
  194. return {op: op, filter: filter};
  195. };
  196. var getQueryParams = function (params, searchQuery, removeempty) {
  197. params.filter = typeof params.filter === 'Object' ? params.filter : (params.filter ? JSON.parse(params.filter) : {});
  198. params.op = typeof params.op === 'Object' ? params.op : (params.op ? JSON.parse(params.op) : {});
  199. params.filter = $.extend({}, params.filter, searchQuery.filter);
  200. params.op = $.extend({}, params.op, searchQuery.op);
  201. //移除empty的值
  202. if (removeempty) {
  203. $.each(params.filter, function (i, j) {
  204. if ((j == '' || j == null || ($.isArray(j) && j.length == 0)) && !params.op[i].match(/null/i)) {
  205. delete params.filter[i];
  206. delete params.op[i];
  207. }
  208. });
  209. }
  210. params.filter = JSON.stringify(params.filter);
  211. params.op = JSON.stringify(params.op);
  212. return params;
  213. };
  214. $.extend($.fn.bootstrapTable.defaults, {
  215. commonSearch: false,
  216. titleForm: "Common search",
  217. actionForm: "",
  218. searchFormTemplate: "",
  219. searchFormVisible: true,
  220. searchClass: 'searchit',
  221. showSearch: true,
  222. renderDefault: true,
  223. onCommonSearch: function (field, text) {
  224. return false;
  225. },
  226. onPostCommonSearch: function (table) {
  227. return false;
  228. }
  229. });
  230. $.extend($.fn.bootstrapTable.defaults.icons, {
  231. commonSearchIcon: 'glyphicon-search'
  232. });
  233. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  234. 'common-search.bs.table': 'onCommonSearch',
  235. 'post-common-search.bs.table': 'onPostCommonSearch'
  236. });
  237. $.extend($.fn.bootstrapTable.locales[$.fn.bootstrapTable.defaults.locale], {
  238. formatCommonSearch: function () {
  239. return "Common search";
  240. },
  241. formatCommonSubmitButton: function () {
  242. return "Submit";
  243. },
  244. formatCommonResetButton: function () {
  245. return "Reset";
  246. },
  247. formatCommonCloseButton: function () {
  248. return "Close";
  249. },
  250. formatCommonChoose: function () {
  251. return "Choose";
  252. }
  253. });
  254. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
  255. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  256. _initHeader = BootstrapTable.prototype.initHeader,
  257. _initToolbar = BootstrapTable.prototype.initToolbar,
  258. _load = BootstrapTable.prototype.load,
  259. _initSearch = BootstrapTable.prototype.initSearch;
  260. BootstrapTable.prototype.initHeader = function () {
  261. _initHeader.apply(this, Array.prototype.slice.apply(arguments));
  262. this.$header.find('th[data-field]').each(function (i) {
  263. var column = $(this).data();
  264. if (typeof column['width'] !== 'undefined' && column['width'].toString().indexOf("%") === -1) {
  265. $(".th-inner", this).outerWidth(column['width']);
  266. $(this).css("max-width", column['width']);
  267. }
  268. });
  269. this.options.stateField = this.header.stateField;
  270. };
  271. BootstrapTable.prototype.initToolbar = function () {
  272. _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
  273. if (!isSearchAvailble(this)) {
  274. return;
  275. }
  276. var that = this,
  277. html = [];
  278. if (that.options.showSearch) {
  279. html.push(sprintf('<div class="columns-%s pull-%s" style="margin-top:10px;margin-bottom:10px;">', this.options.buttonsAlign, this.options.buttonsAlign));
  280. 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()));
  281. html.push(sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.commonSearchIcon))
  282. html.push('</button></div>');
  283. }
  284. if (that.$toolbar.find(".pull-right").size() > 0) {
  285. $(html.join('')).insertBefore(that.$toolbar.find(".pull-right:first"));
  286. } else {
  287. that.$toolbar.append(html.join(''));
  288. }
  289. initCommonSearch(that.columns, that);
  290. that.$toolbar.find('button[name="commonSearch"]')
  291. .off('click').on('click', function () {
  292. that.$commonsearch.toggleClass("hidden");
  293. return;
  294. });
  295. that.$container.on("click", "." + that.options.searchClass, function () {
  296. var value = $(this).data("value");
  297. var field = $(this).data("field");
  298. var ul = that.$container.closest(".panel-intro").find("ul[data-field='" + field + "']");
  299. if (ul.length > 0) {
  300. $('li a[data-value="' + value + '"][data-toggle="tab"]', ul).trigger('click');
  301. return;
  302. }
  303. var obj = $("form [name='" + field + "']", that.$commonsearch);
  304. if (obj.size() > 0) {
  305. if (obj.is("select")) {
  306. $("option[value='" + value + "']", obj).prop("selected", true);
  307. } else if (obj.size() > 1) {
  308. $("form [name='" + field + "'][value='" + value + "']", that.$commonsearch).prop("checked", true);
  309. } else {
  310. obj.val(value + "");
  311. }
  312. obj.trigger("change");
  313. $("form", that.$commonsearch).trigger("submit");
  314. }
  315. });
  316. var queryParams = that.options.queryParams;
  317. //匹配默认搜索值
  318. this.options.queryParams = function (params) {
  319. return queryParams(getQueryParams(params, getSearchQuery(that, true)));
  320. };
  321. this.trigger('post-common-search', that);
  322. };
  323. BootstrapTable.prototype.onCommonSearch = function () {
  324. var searchQuery = getSearchQuery(this);
  325. this.trigger('common-search', this, searchQuery);
  326. this.options.pageNumber = 1;
  327. //this.options.pageSize = $.fn.bootstrapTable.defaults.pageSize;
  328. this.refresh({});
  329. };
  330. BootstrapTable.prototype.load = function (data) {
  331. _load.apply(this, Array.prototype.slice.apply(arguments));
  332. if (!isSearchAvailble(this)) {
  333. return;
  334. }
  335. };
  336. BootstrapTable.prototype.initSearch = function () {
  337. _initSearch.apply(this, Array.prototype.slice.apply(arguments));
  338. if (!isSearchAvailble(this)) {
  339. return;
  340. }
  341. var that = this;
  342. var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
  343. this.data = fp ? $.grep(this.data, function (item, i) {
  344. for (var key in fp) {
  345. var fval = fp[key].toLowerCase();
  346. var value = item[key];
  347. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
  348. that.header.formatters[$.inArray(key, that.header.fields)],
  349. [value, item, i], value);
  350. if (!($.inArray(key, that.header.fields) !== -1 &&
  351. (typeof value === 'string' || typeof value === 'number') &&
  352. (value + '').toLowerCase().indexOf(fval) !== -1)) {
  353. return false;
  354. }
  355. }
  356. return true;
  357. }) : this.data;
  358. };
  359. }(jQuery);