bootstrap-table-commonsearch.js 18 KB

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