zhyd.table.js 13.2 KB
Newer Older
Y
yadong.zhang 已提交
1 2 3 4 5 6 7 8 9
/**
 *
 * bootstrap-table工具类
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @date 2018-04-22
 * @since 1.0
 */
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
function Table(options) {
    this.options = $.extend({
        tableBox: "#tablelist"
    }, options);
}

Table.prototype = {
    init: function (callback) {
        this.createTable();
        this.bindBtnEvent(callback);
        return this;
    },
    createTable: function () {
        var $table = this;
        var options = this.options;
        var $tablelist = $(options.tableBox);
        $tablelist.bootstrapTable('destroy').bootstrapTable({
            url: options.url,
            method: 'post',                      //请求方式(*)
            toolbar: options.showToolbar !== false ? options.toolbar ? options.toolbar : '#toolbar' : '',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
            contentType: "application/x-www-form-urlencoded", // 发送到服务器的数据编码类型, application/x-www-form-urlencoded为了实现post方式提交
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            sortStable: true,                   // 设置为 true 将获得稳定的排序
            queryParams: $table.queryParams,//传递参数(*)
            queryParamsType: '',
            pagination: true,                   //是否显示分页(*)
            sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
            pageNumber: 1,                       //初始化加载第一页,默认第一页
            pageSize: 20,                       //每页的记录行数(*)
            pageList: [20, 40, 50, 100, 150],        //可供选择的每页的行数(*)
            search: options.search !== false,      //是否启用搜索框 根据sidePagination选择从前后台搜索
            strictSearch: true,                 //设置为 true启用 全匹配搜索,否则为模糊搜索
            searchOnEnterKey: true,            // 设置为 true时,按回车触发搜索方法,否则自动触发搜索方法
            minimumCountColumns: 1,             //最少允许的列数
            // showColumns: true,                  //是否显示 内容列下拉框
            showRefresh: true,                  //是否显示刷新按钮
            // showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
            iconsPrefix: 'fa', // glyphicon of fa (font awesome)
            icons: {
                refresh: 'fa-refresh icon-refresh',
                toggle: 'fa-list-alt icon-list-alt',
                columns: 'fa-th icon-th',
                detailOpen: 'fa-plus icon-plus',
                detailClose: 'fa-minus icon-minus'
            },
            // detailView: true,                   //是否显示父子表
            // showExport: true,                   //是否显示导出
            // exportDataType: "basic",              //basic', 'all', 'selected'.
            // clickToSelect: true,                //是否启用点击选中行
            // singleSelect: true,
            height: 640,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
            onEditableSave: function (field, row, oldValue, $el) {
                if (options.updateUrl) {
                    $.ajax({
                        type: "post",
                        url: options.updateUrl,
                        data: {strJson: JSON.stringify(row)},
                        success: function (json) {
                            if (json.status == 200) {
                                $.alert.info(json.message);
                            } else {
                                $.alert.error(json.message);
                            }
                        },
                        error: function () {
                            $.alert.error("网络超时!");
Y
yadong.zhang 已提交
79
                        }
80 81 82 83 84 85 86 87 88
                    });
                } else {
                    $.alert.error("无效的请求地址!");
                    return false;
                }
            },
            onLoadSuccess: function () {
                console.log("table加载完成");
                setTimeout(function () {
89
                    gentelella.initSwitchery();
90
                }, 0);
Y
yadong.zhang 已提交
91
            },
92 93 94
            onExpandRow: options.onExpandRow,
            rowStyle: options.rowStyle || function (row, index) {
                return {};
Y
yadong.zhang 已提交
95
            },
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
            columns: options.columns
        });
    },
    bindBtnEvent: function (callback) {
        var $table = this;
        var options = this.options;
        /* 添加 */
        $("#btn_add").click(function () {
            $table.resetForm();
            var $modal = $("#addOrUpdateModal");

            $modal.modal('show');
            $modal.find(".modal-dialog .modal-content .modal-header .modal-title").html("添加" + options.modalName);

            var $password = $("#password");
            if ($password && $password[0]) {
                $password.attr("required", "required");
            }
            var $username = $("#username");
            if ($username && $username[0]) {
                $username.removeAttr("readonly");
Y
yadong.zhang 已提交
117
            }
118 119
            $table.bindSaveInfoEvent(options.createUrl, callback);
        });
Y
yadong.zhang 已提交
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        /* 修改 */
        this.bindClickEvent('.btn-update', function () {
            var $this = $(this);
            var userId = $this.attr("data-id");
            $.ajax({
                type: "post",
                url: options.getInfoUrl.replace("{id}", userId),
                success: function (json) {
                    if(json.status != 200) {
                        $.alert.error(json.message);
                        return;
                    }
                    var info = json.data;
                    // console.log(info);
                    $table.resetForm(info);
                    var $modal = $("#addOrUpdateModal");
                    $modal.modal('show');
                    $modal.find(".modal-dialog .modal-content .modal-header .modal-title").html("修改" + options.modalName);
139 140
                    var $password = $("#password");
                    if ($password && $password[0]) {
141
                        $password.removeAttr("required");
Y
yadong.zhang 已提交
142
                    }
143 144
                    var $username = $("#username");
                    if ($username && $username[0]) {
145
                        $username.attr("readonly", "readonly");
Y
yadong.zhang 已提交
146
                    }
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

                    $table.bindSaveInfoEvent(options.updateUrl, callback);

                },
                error: $.alert.ajaxError
            });
        });

        /* 删除 */
        function remove(ids) {
            $.alert.confirm("确定删除该" + options.modalName + "信息?", function () {
                $.ajax({
                    type: "post",
                    url: options.removeUrl,
                    traditional: true,
                    data: {'ids': ids},
                    success: function (json) {
                        $.alert.ajaxSuccess(json);
                        $table.refresh();
                    },
                    error: $.alert.ajaxError
Y
yadong.zhang 已提交
168
                });
169
            }, function () {
Y
yadong.zhang 已提交
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
            }, 5000);
        }

        /* 批量删除用户 */
        $("#btn_delete_ids").click(function () {
            var selectedId = $table.getSelectedIds();
            if (!selectedId || selectedId == '[]' || selectedId.length == 0) {
                $.alert.error("请至少选择一条记录");
                return;
            }
            remove(selectedId);
        });

        this.bindClickEvent('.btn-remove', function () {
            var $this = $(this);
            var userId = $this.attr("data-id");
            remove(userId);
        });
    },
    bindEvent: function(eventName, selector, callback){
        var options = this.options;
        $(options.tableBox).on(eventName, selector, callback);
    },
    bindClickEvent: function(selector, callback) {
        this.bindEvent("click", selector, callback);
    },
    queryParams: function (params) {
        params = $.extend({}, params);
        params.keywords = params.searchText;
        return params;
    },
    refresh: function () {
        var options = this.options;
        $(options.tableBox).bootstrapTable('refresh', {url: options.url});
    },
    getSelectedIds: function () {
        var selectedJson = this.getSelections();
        var ids = [];
        $.each(selectedJson, function (i) {
            ids.push(selectedJson[i].id);
        });
        return ids;
    },
    getSelections: function () {
        var options = this.options;
        return $(options.tableBox).bootstrapTable('getAllSelections')
    },
    isMultipartForm: function (form) {
        var $form = $(form),
            enctype = $form.attr("enctype");
        return enctype && enctype === "multipart/form-data";
    },
    bindSaveInfoEvent: function (url, callback) {
        var $table = this;
        var $form = $("#addOrUpdateForm"),
            $submitBtn = $(".addOrUpdateBtn"),
            $modal = $("#addOrUpdateModal");
        $submitBtn.unbind('click');
        callback && callback();
        $submitBtn.click(function () {
            if (validator.checkAll($form)) {
                if ($table.isMultipartForm($form)) {
                    $form.ajaxSubmit({
                        type: 'post',
                        url: url,
                        success: function (json) {
                            $.alert.ajaxSuccess(json);
                            if(json.status == 200) {
                                $modal.modal('hide');
                            }
                            $table.refresh();
                        },
                        error: $.alert.ajaxError
                    });
                } else {
Y
yadong.zhang 已提交
246 247
                    $.ajax({
                        type: "post",
248 249
                        url: url,
                        data: $form.serialize(),
Y
yadong.zhang 已提交
250
                        success: function (json) {
251 252 253
                            $.alert.ajaxSuccess(json);
                            if(json.status == 200) {
                                $modal.modal('hide');
Y
yadong.zhang 已提交
254
                            }
255
                            $table.refresh();
Y
yadong.zhang 已提交
256
                        },
Y
yadong.zhang 已提交
257
                        error: $.alert.ajaxError
Y
yadong.zhang 已提交
258 259 260
                    });
                }
            }
261 262 263 264 265 266 267 268 269 270 271 272
        })
    },
    resetForm: function (info) {
        var $table = this;
        $("#addOrUpdateModal form input,#addOrUpdateModal form select,#addOrUpdateModal form textarea").each(function () {
            var $this = $(this);
            $table.clearText($this, this.type, info);
        });
    },
    clearText: function ($this, type, info) {
        if($this.hasClass("final") || $this.data("final")) {
            return;
Y
yadong.zhang 已提交
273
        }
274 275 276 277
        var $div = $this.parents(".item");
        if ($div && $div.hasClass("bad")) {
            $div.removeClass("bad");
            $div.find("div.alert").remove();
Y
yadong.zhang 已提交
278
        }
279 280 281
        if (info == undefined) {
            $("div[id^='text-']").empty();
            $("div[id^='text-']").append("<p><br/><br/></p>");
282
        }
283 284 285 286 287 288 289 290 291 292 293

        if (info) {
            var thisName = $this.attr("name");
            if (("undefined" == typeof thisName)) {
                return;
            }
            var thisValue;
            if (thisName.indexOf(".") !== -1) {
                var nodeObj = info[thisName.split(".")[0]];
                if (nodeObj) {
                    thisValue = nodeObj[thisName.split(".")[1]];
294
                }
295 296
            } else {
                thisValue = info[thisName];
297
            }
298 299 300 301 302 303 304 305 306 307
            if (type == 'radio') {
                $this.iCheck(((thisValue && 1 == $this.val()) || (!thisValue && 0 == $this.val())) ? 'check' : 'uncheck')
            } else if (type.startsWith('select')) {
                if (thisValue == 'true' || thisValue == true) {
                    thisValue = 1;
                } else if (thisValue == 'false' || thisValue == false) {
                    thisValue = 0;
                }
                $this.val(thisValue);
            } else if (type == "textarea" && $("#" + thisName).prev().find("div[id^='text-']").length > 0) {
308

309 310 311 312 313 314 315 316 317 318 319
                $("#" + thisName).prev().find("div[id^='text-']").empty();
                $("#" + thisName).prev().find("div[id^='text-']").append(thisValue);
            } else {
                if(type == 'file') {
                    var previewContainer = $this.data("preview-container");
                    if(previewContainer) {
                        $(previewContainer).html('<img src="' + thisValue + '" class="img-responsive img-rounded auto-shake" alt="">')
                    }
                    return;
                }
                $this.val(thisValue);
Y
yadong.zhang 已提交
320
            }
Y
yadong.zhang 已提交
321
        } else {
322 323
            if (type === 'radio' || type === 'checkbox') {
                $this.iCheck('uncheck');
324 325 326
            } else {
                $this.val('');
            }
Y
yadong.zhang 已提交
327 328
        }
    }
329
};
Y
yadong.zhang 已提交
330 331