审查视图

public/assets/js/bootstrap-table-advancedsearch.js 12.5 KB
Karson authored
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
/**
 * @author: aperez <aperez@datadec.es>
 * @version: v2.0.0
 *
 * @update Dennis Hernández <http://djhvscf.github.io/Blog>
 */

!function ($) {
    'use strict';

    var firstLoad = false;

    var sprintf = $.fn.bootstrapTable.utils.sprintf;

    var showAvdSearch = function (pColumns, that) {
        var searchTitle = that.options.formatAdvancedSearch();
        if (!$("#avdSearchModal" + "_" + that.options.idTable).hasClass("modal")) {
            var vModal = sprintf("<div id=\"avdSearchModal%s\"  class=\"modal fade\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\" aria-hidden=\"true\">", "_" + that.options.idTable);
            vModal += "<div class=\"modal-dialog modal-xs\">";
            vModal += " <div class=\"modal-content\">";
            vModal += "  <div class=\"modal-header\">";
            vModal += "   <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\" >&times;</button>";
            vModal += sprintf("   <h4 class=\"modal-title\">%s</h4>", searchTitle);
            vModal += "  </div>";
            vModal += "  <div class=\"modal-body modal-body-custom\">";
            vModal += sprintf("   <div class=\"container-fluid\" id=\"avdSearchModalContent%s\" style=\"padding-right: 0px;padding-left: 0px;\" >", "_" + that.options.idTable);
            vModal += "   </div>";
            vModal += "  </div>";
            vModal += "  <div class=\"modal-footer\">";
            vModal += createFormBtn(that).join('');
            vModal += "  </div>";
            vModal += "  </div>";
            vModal += " </div>";
            vModal += "</div>";

            $("body").append($(vModal));

            var vFormAvd = createFormAvd(pColumns, that),
                    timeoutId = 0;
            ;

            $('#avdSearchModalContent' + "_" + that.options.idTable).append(vFormAvd.join(''));


            if (that.options.sidePagination != 'server' || !that.options.url) {
                $('#' + that.options.idForm).off('keyup blur', 'input').on('keyup blur', 'input', function (event) {
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function () {
                        that.onColumnAdvancedSearch(event);
                    }, that.options.searchTimeOut);
                });
            } else {

            }
            // 提交搜索
            $("#btnSubmitAvd" + "_" + that.options.idTable).click(function (event) {
                that.onColumnAdvancedSearch();
            });
            // 重置搜索
            $("#btnResetAvd" + "_" + that.options.idTable).click(function () {
                $("#avdSearchModal" + "_" + that.options.idTable + " form")[0].reset();
                that.onColumnAdvancedSearch();
            });

            $("#avdSearchModal" + "_" + that.options.idTable).modal();
        } else {
            $("#avdSearchModal" + "_" + that.options.idTable).modal();
        }
    };

    var createFormAvd = function (pColumns, that) {
        var htmlForm = [];
        var opList = ['=', '>', '>=', '<', '<=', '!=', 'LIKE', 'LIKE %...%', 'NOT LIKE', 'IN(...)', 'NOT IN(...)', 'BETWEEN', 'NOT BETWEEN', 'IS NULL', 'IS NOT NULL'];
        var selectList = [];
        for (var i = 0; i < opList.length; i++) {
            selectList.push("<option value='" + opList[i] + "'>" + opList[i] + "</option>");
        }
        var selectHtml = selectList.join('');
        htmlForm.push(sprintf('<form class="form-horizontal" id="%s" action="%s" >', that.options.idForm, that.options.actionForm));
        for (var i in pColumns) {
            var vObjCol = pColumns[i];
            if (!vObjCol.checkbox && vObjCol.field != 'operate' && vObjCol.visible && vObjCol.searchable) {
                htmlForm.push('<div class="form-group">');
                htmlForm.push(sprintf('<label class="col-sm-3 control-label">%s</label>', vObjCol.title));
                if (that.options.sidePagination == 'server' && that.options.url) {
                    htmlForm.push('<div class="col-sm-2">');
                    htmlForm.push(sprintf('<select class="form-control" name="field-%s" data-name="%s">%s</select>', vObjCol.field, vObjCol.field, selectHtml));
                    htmlForm.push('</div>');
                }
90
Karson authored
91
                htmlForm.push('<div class="col-sm-6">');
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
                if (vObjCol.searchList) {
                    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>', $.fn.bootstrapTable.locales.formatAdvancedChoose()));
                        $.each(vObjCol.searchList, function (key, value) {
                            searchList.push("<option value='" + (isArray ? value : key) + "'>" + value + "</option>");
                        });
                        htmlForm.push(sprintf('<select class="form-control" name="%s">%s</select>', vObjCol.field, searchList.join('')));
                    }
                } else {
                    htmlForm.push(sprintf('<input type="text" class="form-control input-md" name="%s" placeholder="%s" id="%s">', vObjCol.field, vObjCol.title, vObjCol.field));
                }
Karson authored
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
                htmlForm.push('</div>');
                htmlForm.push('</div>');
            }
        }

        htmlForm.push('</form>');

        return htmlForm;
    };

    var createFormBtn = function (that) {
        var htmlBtn = [];
        var searchSubmit = that.options.formatAdvancedSubmitButton();
        var searchReset = that.options.formatAdvancedResetButton();
        var searchClose = that.options.formatAdvancedCloseButton();
        htmlBtn.push('<div class="form-group">');
        htmlBtn.push('<div class="col-sm-12 text-center">');
        if (that.options.sidePagination == 'server' && that.options.url) {
            htmlBtn.push(sprintf('<button type="button" id="btnSubmitAvd%s" class="btn btn-success" >%s</button> ', "_" + that.options.idTable, searchSubmit));
            htmlBtn.push(sprintf('<button type="button" id="btnResetAvd%s" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchReset));
        } else {
            htmlBtn.push(sprintf('<button type="button" id="btnCloseAvd%s" data-dismiss="modal" class="btn btn-default" >%s</button> ', "_" + that.options.idTable, searchClose));
        }
        htmlBtn.push('</div>');
        htmlBtn.push('</div>');
        return htmlBtn;
    };

    $.extend($.fn.bootstrapTable.defaults, {
        advancedSearch: false,
        idForm: 'advancedSearch',
        actionForm: '',
        idTable: undefined,
        onColumnAdvancedSearch: function (field, text) {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.defaults.icons, {
        advancedSearchIcon: 'glyphicon-search'
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'column-advanced-search.bs.table': 'onColumnAdvancedSearch'
    });
    $.extend($.fn.bootstrapTable.locales, {
        formatAdvancedSearch: function () {
155
            return __('Advanced search');
Karson authored
156 157
        },
        formatAdvancedSubmitButton: function () {
158
            return __("Submit");
Karson authored
159 160
        },
        formatAdvancedResetButton: function () {
161
            return __("Reset");
Karson authored
162 163
        },
        formatAdvancedCloseButton: function () {
164
            return __("Close");
165 166
        },
        formatAdvancedChoose: function () {
167
            return __("Choose");
Karson authored
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
        }
    });

    $.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 (!this.options.search) {
            return;
        }

        if (!this.options.advancedSearch) {
            return;
        }

        if (!this.options.idTable) {
            return;
        }

        var that = this,
                html = [];

        html.push(sprintf('<div class="columns columns-%s btn-group pull-%s" role="group">', this.options.buttonsAlign, this.options.buttonsAlign));
        html.push(sprintf('<button class="btn btn-default%s' + '" type="button" name="advancedSearch" title="%s">', that.options.iconSize === undefined ? '' : ' btn-' + that.options.iconSize, that.options.formatAdvancedSearch()));
        html.push(sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.advancedSearchIcon))
        html.push('</button></div>');

        that.$toolbar.prepend(html.join(''));

        that.$toolbar.find('button[name="advancedSearch"]')
                .off('click').on('click', function () {
            showAvdSearch(that.columns, that);
        });
    };

    BootstrapTable.prototype.load = function (data) {
        _load.apply(this, Array.prototype.slice.apply(arguments));

        if (!this.options.advancedSearch) {
            return;
        }

        if (typeof this.options.idTable === 'undefined') {
            return;
        } else {
            if (!firstLoad) {
                var height = parseInt($(".bootstrap-table").height());
                height += 10;
                $("#" + this.options.idTable).bootstrapTable("resetView", {height: height});
                firstLoad = true;
            }
        }
    };

    BootstrapTable.prototype.initSearch = function () {
        _initSearch.apply(this, Array.prototype.slice.apply(arguments));

        if (!this.options.advancedSearch) {
            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.onColumnAdvancedSearch = function (event) {
        if (typeof event == 'undefined') {
            var op = {};
            var filter = {};
            $("#avdSearchModalContent_" + this.options.idTable + " select").each(function () {
                var name = $(this).data("name");
                var sym = $(this).val();
262 263 264 265
                var obj = $("[name='" + name + "']");
                if (obj.size() == 0)
                    return true;
                var value = obj.size() > 1 ? $("[name='" + name + "']:checked").val() : obj.val();
Karson authored
266 267 268 269 270 271 272 273 274
                if (value == '' && sym.indexOf("NULL") == -1) {
                    return true;
                }

                op[name] = sym;
                filter[name] = value;
            });
            // 追加查询关键字
            this.options.pageNumber = 1;
275 276 277 278 279 280 281 282 283 284 285
            this.options.queryParams = function (params) {
                return {
                    search: params.search,
                    sort: params.sort,
                    order: params.order,
                    filter: JSON.stringify(filter),
                    op: JSON.stringify(op),
                    offset: params.offset,
                    limit: params.limit,
                };
            };
Karson authored
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
            this.refresh({query: {filter: JSON.stringify(filter), op: JSON.stringify(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-advanced-search', $field, text);
        }
    };
}(jQuery);