bootstrap-table-commonsearch.js 18 KB

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