bootstrap-table-commonsearch.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 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.searchable && vObjCol.operate !== false) {
  73. ColumnsForSearch.push(vObjCol);
  74. htmlForm.push('<div class="form-group" style="margin:5px">');
  75. htmlForm.push(sprintf('<label for="%s" class="control-label" style="padding:0 10px">%s</label>', vObjCol.field, vObjCol.title));
  76. if (that.options.sidePagination == 'server' && that.options.url) {
  77. //htmlForm.push('<div class="col-sm-2">');
  78. //htmlForm.push(sprintf('<select class="form-control" name="field-%s" data-name="%s">%s</select>', vObjCol.field, vObjCol.field, selectHtml));
  79. vObjCol.operate = (typeof vObjCol.operate === 'undefined' || $.inArray(vObjCol.operate, opList) === -1) ? '=' : vObjCol.operate;
  80. 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));
  81. //htmlForm.push('</div>');
  82. }
  83. //htmlForm.push('<div class="col-sm-8">');
  84. var style = typeof vObjCol.style === 'undefined' ? '' : sprintf('style="%s"', vObjCol.style);
  85. if (vObjCol.searchList) {
  86. if (typeof vObjCol.searchList == 'function') {
  87. htmlForm.push(vObjCol.searchList.call(this, vObjCol));
  88. } else {
  89. var isArray = vObjCol.searchList.constructor === Array;
  90. var searchList = [];
  91. searchList.push(sprintf('<option value="">%s</option>', $.fn.bootstrapTable.locales.formatCommonChoose()));
  92. $.each(vObjCol.searchList, function (key, value) {
  93. searchList.push("<option value='" + (isArray ? value : key) + "'>" + value + "</option>");
  94. });
  95. htmlForm.push(sprintf('<select class="form-control" name="%s" %s>%s</select>', vObjCol.field, style, searchList.join('')));
  96. }
  97. } else {
  98. var placeholder = typeof vObjCol.placeholder === 'undefined' ? vObjCol.title : vObjCol.placeholder;
  99. var type = typeof vObjCol.type === 'undefined' ? 'text' : vObjCol.type;
  100. var addclass = typeof vObjCol.addclass === 'undefined' ? 'form-control' : 'form-control ' + vObjCol.addclass;
  101. var data = typeof vObjCol.data === 'undefined' ? '' : vObjCol.data;
  102. 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));
  103. var reg = /BETWEEN$/;
  104. if (reg.test(vObjCol.operate)) {
  105. 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));
  106. }
  107. }
  108. //htmlForm.push('</div>');
  109. htmlForm.push('</div>');
  110. }
  111. }
  112. htmlForm.push(createFormBtn(that).join(''));
  113. htmlForm.push('</fieldset>');
  114. htmlForm.push('</form>');
  115. return htmlForm;
  116. };
  117. var createFormBtn = function (that) {
  118. var htmlBtn = [];
  119. var searchSubmit = that.options.formatCommonSubmitButton();
  120. var searchReset = that.options.formatCommonResetButton();
  121. var searchClose = that.options.formatCommonCloseButton();
  122. htmlBtn.push('<div class="form-group" style="margin:5px">');
  123. htmlBtn.push('<div class="col-sm-12 text-center">');
  124. if (that.options.sidePagination == 'server' && that.options.url) {
  125. htmlBtn.push(sprintf('<button type="button" id="btnSubmitCommon%s" class="btn btn-success" >%s</button> ', "_" + that.options.idTable, searchSubmit));
  126. htmlBtn.push(sprintf('<button type="button" id="btnResetCommon%s" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchReset));
  127. } else {
  128. htmlBtn.push(sprintf('<button type="button" id="btnCloseCommon%s" data-dismiss="modal" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchClose));
  129. }
  130. htmlBtn.push('</div>');
  131. htmlBtn.push('</div>');
  132. return htmlBtn;
  133. };
  134. $.extend($.fn.bootstrapTable.defaults, {
  135. commonSearch: false,
  136. idForm: 'commonSearch',
  137. titleForm: __("Common search"),
  138. actionForm: '',
  139. idTable: undefined,
  140. onColumnCommonSearch: function (field, text) {
  141. return false;
  142. }
  143. });
  144. $.extend($.fn.bootstrapTable.defaults.icons, {
  145. commonSearchIcon: 'glyphicon-search'
  146. });
  147. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  148. 'column-common-search.bs.table': 'onColumnCommonSearch'
  149. });
  150. $.extend($.fn.bootstrapTable.locales, {
  151. formatCommonSearch: function () {
  152. return __("Common search");
  153. },
  154. formatCommonSubmitButton: function () {
  155. return __("Submit");
  156. },
  157. formatCommonResetButton: function () {
  158. return __("Reset");
  159. },
  160. formatCommonCloseButton: function () {
  161. return __("Close");
  162. },
  163. formatCommonChoose: function () {
  164. return __("Choose");
  165. }
  166. });
  167. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
  168. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  169. _initToolbar = BootstrapTable.prototype.initToolbar,
  170. _load = BootstrapTable.prototype.load,
  171. _initSearch = BootstrapTable.prototype.initSearch;
  172. BootstrapTable.prototype.initToolbar = function () {
  173. _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
  174. if (!this.options.search) {
  175. return;
  176. }
  177. if (!this.options.commonSearch) {
  178. return;
  179. }
  180. if (!this.options.idTable) {
  181. return;
  182. }
  183. var that = this;
  184. showCommonSearch(that.columns, that);
  185. };
  186. BootstrapTable.prototype.load = function (data) {
  187. _load.apply(this, Array.prototype.slice.apply(arguments));
  188. if (!this.options.commonSearch) {
  189. return;
  190. }
  191. if (typeof this.options.idTable === 'undefined') {
  192. return;
  193. } else {
  194. if (!firstLoad) {
  195. var height = parseInt($(".bootstrap-table").height());
  196. height += 10;
  197. $("#" + this.options.idTable).bootstrapTable("resetView", {height: height});
  198. firstLoad = true;
  199. }
  200. }
  201. };
  202. BootstrapTable.prototype.initSearch = function () {
  203. _initSearch.apply(this, Array.prototype.slice.apply(arguments));
  204. if (!this.options.commonSearch) {
  205. return;
  206. }
  207. var that = this;
  208. var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
  209. this.data = fp ? $.grep(this.data, function (item, i) {
  210. for (var key in fp) {
  211. var fval = fp[key].toLowerCase();
  212. var value = item[key];
  213. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
  214. that.header.formatters[$.inArray(key, that.header.fields)],
  215. [value, item, i], value);
  216. if (!($.inArray(key, that.header.fields) !== -1 &&
  217. (typeof value === 'string' || typeof value === 'number') &&
  218. (value + '').toLowerCase().indexOf(fval) !== -1)) {
  219. return false;
  220. }
  221. }
  222. return true;
  223. }) : this.data;
  224. };
  225. BootstrapTable.prototype.onColumnCommonSearch = function (event) {
  226. if (typeof event === 'undefined') {
  227. var op = {};
  228. var filter = {};
  229. $("#commonSearchModalContent_" + this.options.idTable + " input.operate").each(function (i) {
  230. var name = $(this).data("name");
  231. var sym = $(this).val();
  232. var obj = $("[name='" + name + "']");
  233. if (obj.size() == 0)
  234. return true;
  235. var vObjCol = ColumnsForSearch[i];
  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. if (typeof vObjCol.process === 'function') {
  243. value_begin = vObjCol.process(value_begin, 'begin');
  244. value_end = vObjCol.process(value_end, 'end');
  245. } else if ($("[name='" + name + "']:first").attr('type') === 'datetime') { //datetime类型字段转换成时间戳
  246. value_begin = strtotime(value_begin);
  247. value_end = strtotime(value_end);
  248. if (value_begin === value_end && '00:00:00' === date('H:i:s', value_begin)) {
  249. value_end += 86399;
  250. }
  251. }
  252. var value = value_begin + ',' + value_end;
  253. } else {
  254. var value = $("[name='" + name + "']:checked").val();
  255. }
  256. } else {
  257. var value = (typeof vObjCol.process === 'function') ? vObjCol.process(obj.val()) : obj.val();
  258. }
  259. if (value == '' && sym.indexOf("NULL") == -1) {
  260. return true;
  261. }
  262. op[name] = sym;
  263. filter[name] = value;
  264. });
  265. // 追加查询关键字
  266. this.options.pageNumber = 1;
  267. this.options.queryParams = function (params) {
  268. return {
  269. search: params.search,
  270. sort: params.sort,
  271. order: params.order,
  272. filter: JSON.stringify(filter),
  273. op: JSON.stringify(op),
  274. offset: params.offset,
  275. limit: params.limit,
  276. };
  277. };
  278. this.refresh({query: {filter: JSON.stringify(filter), op: JSON.stringify(op)}});
  279. } else {
  280. var text = $.trim($(event.currentTarget).val());
  281. var $field = $(event.currentTarget)[0].id;
  282. if ($.isEmptyObject(this.filterColumnsPartial)) {
  283. this.filterColumnsPartial = {};
  284. }
  285. if (text) {
  286. this.filterColumnsPartial[$field] = text;
  287. } else {
  288. delete this.filterColumnsPartial[$field];
  289. }
  290. this.options.pageNumber = 1;
  291. this.onSearch(event);
  292. // this.updatePagination();
  293. this.trigger('column-common-search', $field, text);
  294. }
  295. };
  296. /**
  297. * 模仿PHP的strtotime()函数
  298. * strtotime('2017-05-20 13:14:00') OR strtotime('2017-05-20')
  299. * @return 时间戳
  300. */
  301. var strtotime = function (str) {
  302. var _arr = str.split(' ');
  303. var _day = _arr[0].split('-');
  304. _arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
  305. var _time = _arr[1].split(':');
  306. for (var i = _day.length - 1; i >= 0; i--) {
  307. _day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
  308. }
  309. for (var i = _time.length - 1; i >= 0; i--) {
  310. _time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
  311. }
  312. var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
  313. return _temp.getTime() / 1000;
  314. };
  315. /**
  316. * 模仿PHP的date()函数
  317. * strtotime('Y-m-d H:i:s');
  318. * @param format 只支持 'Y-m-d H:i:s','Y-m-d','H:i:s' 三种调用方式
  319. * @param time 为空时,取当前时间
  320. * @return 日期格式化的字符串
  321. */
  322. var date = function (format, time) {
  323. var _temp = (time != null) ? new Date(time * 1000) : new Date();
  324. var _return = '';
  325. if (/Y-m-d/.test(format)) {
  326. var _day = [_temp.getFullYear(), addzero(1 + _temp.getMonth()), addzero(_temp.getDate())];
  327. _return = _day.join('-');
  328. }
  329. if (/H:i:s/.test(format)) {
  330. var _time = [addzero(_temp.getHours()), addzero(_temp.getMinutes()), addzero(_temp.getSeconds())];
  331. _return += ' ' + _time.join(':');
  332. }
  333. return _return.replace(/^\s+|\s+$/gm, '');
  334. function addzero(i) {
  335. if (i <= 9) {
  336. return '0' + i;
  337. } else {
  338. return i;
  339. }
  340. }
  341. };
  342. }(jQuery);