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