zhyd.table.js 12.0 KB
Newer Older
Y
yadong.zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 *
 * bootstrap-table工具类
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @website https://www.zhyd.me
 * @version 1.0
 * @date 2018-04-22
 * @since 1.0
 */
(function ($) {
    $.extend({
        tableUtil: {
            _option: {},
            init: function (options) {
                $.tableUtil._option = options;
智布道's avatar
智布道 已提交
17 18
                var $tablelist = $('#tablelist');
                $tablelist.bootstrapTable('destroy').bootstrapTable({
Y
yadong.zhang 已提交
19 20 21 22
                    url: options.url,
                    method: 'post',                      //请求方式(*)
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
智布道's avatar
智布道 已提交
23
                    cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
Y
yadong.zhang 已提交
24 25 26 27 28 29 30 31 32
                    contentType: "application/x-www-form-urlencoded", // 发送到服务器的数据编码类型, application/x-www-form-urlencoded为了实现post方式提交
                    sortable: false,                     //是否启用排序
                    sortOrder: "asc",                   //排序方式
                    sortStable: true,                   // 设置为 true 将获得稳定的排序
                    queryParams: $.tableUtil.queryParams,//传递参数(*)
                    queryParamsType: '',
                    pagination: true,                   //是否显示分页(*)
                    sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
                    pageNumber: 1,                       //初始化加载第一页,默认第一页
33 34
                    pageSize: 20,                       //每页的记录行数(*)
                    pageList: [20, 40, 50, 100, 150],        //可供选择的每页的行数(*)
Y
yadong.zhang 已提交
35 36 37 38
                    search: true,                       //是否启用搜索框 根据sidePagination选择从前后台搜索
                    strictSearch: true,                 //设置为 true启用 全匹配搜索,否则为模糊搜索
                    searchOnEnterKey: true,            // 设置为 true时,按回车触发搜索方法,否则自动触发搜索方法
                    minimumCountColumns: 1,             //最少允许的列数
39
                    // showColumns: true,                  //是否显示 内容列下拉框
Y
yadong.zhang 已提交
40
                    showRefresh: true,                  //是否显示刷新按钮
41 42 43 44 45 46 47 48 49 50 51
                    // showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                    iconsPrefix: 'fa', // glyphicon of fa (font awesome)
                    icons: {
                        // paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
                        // paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
                        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'
                    },
Y
yadong.zhang 已提交
52 53 54 55 56
                    // detailView: true,                   //是否显示父子表
                    // showExport: true,                   //是否显示导出
                    // exportDataType: "basic",              //basic', 'all', 'selected'.
                    // clickToSelect: true,                //是否启用点击选中行
                    // singleSelect: true,
57
                    height: 440,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
Y
yadong.zhang 已提交
58 59 60 61 62 63 64 65
                    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) {
Y
yadong.zhang 已提交
66
                                        $.alert.info(json.message);
Y
yadong.zhang 已提交
67
                                    } else {
Y
yadong.zhang 已提交
68
                                        $.alert.error(json.message);
Y
yadong.zhang 已提交
69 70 71
                                    }
                                },
                                error: function () {
Y
yadong.zhang 已提交
72
                                    $.alert.error("网络超时!");
Y
yadong.zhang 已提交
73 74 75
                                }
                            });
                        } else {
Y
yadong.zhang 已提交
76 77
                            $.alert.error("无效的请求地址!");
                            return false;
Y
yadong.zhang 已提交
78 79
                        }
                    },
智布道's avatar
智布道 已提交
80
                    onExpandRow: options.onExpandRow,
81 82 83
                    rowStyle: options.rowStyle || function (row, index) {
                        return {};
                    },
Y
yadong.zhang 已提交
84 85
                    columns: options.columns
                });
86
                $tablelist.on('load-success.bs.table', function (data) {
87
                    gentelella.initSwitchery();
智布道's avatar
智布道 已提交
88
                });
Y
yadong.zhang 已提交
89 90 91
            },
            queryParams: function (params) {
                params = $.extend({}, params);
92
                params.keywords = params.searchText;
Y
yadong.zhang 已提交
93 94 95 96 97 98 99 100 101 102 103
                return params;
            },
            refresh: function () {
                $("#tablelist").bootstrapTable('refresh', {url: $.tableUtil._option.url});
            }
        },
        buttonUtil: {
            init: function (options) {
                /* 添加 */
                $("#btn_add").click(function () {
                    resetForm();
104 105 106
                    var $addOrUpdateModal = $("#addOrUpdateModal");
                    $addOrUpdateModal.modal('show');
                    $addOrUpdateModal.find(".modal-dialog .modal-content .modal-header h4.modal-title").html("添加" + options.modalName);
Y
yadong.zhang 已提交
107

108 109 110
                    var $password = $("#password");
                    if ($password && $password[0]) {
                        $password.attr("required", "required");
Y
yadong.zhang 已提交
111
                    }
112 113 114
                    var $username = $("#username");
                    if ($username && $username[0]) {
                        $username.removeAttr("readonly");
Y
yadong.zhang 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128
                    }
                    bindSaveInfoEvent(options.createUrl);
                });

                /* 修改 */
                $('#tablelist').on('click', '.btn-update', function () {
                    var $this = $(this);
                    var userId = $this.attr("data-id");
                    $.ajax({
                        type: "post",
                        url: options.getInfoUrl.replace("{id}", userId),
                        success: function (json) {
                            var info = json.data;
                            resetForm(info);
129 130 131 132 133 134
                            var $addOrUpdateModal = $("#addOrUpdateModal");
                            $addOrUpdateModal.modal('show');
                            $addOrUpdateModal.find(".modal-dialog .modal-content .modal-header h4.modal-title").html("修改" + options.modalName);
                            var $password = $("#password");
                            if ($password && $password[0]) {
                                $password.removeAttr("required");
Y
yadong.zhang 已提交
135
                            }
136 137 138
                            var $username = $("#username");
                            if ($username && $username[0]) {
                                $username.attr("readonly", "readonly");
Y
yadong.zhang 已提交
139 140 141 142 143
                            }

                            bindSaveInfoEvent(options.updateUrl);

                        },
Y
yadong.zhang 已提交
144
                        error: $.alert.ajaxError
Y
yadong.zhang 已提交
145 146 147 148 149
                    });
                });

                /* 删除 */
                function remove(ids) {
Y
yadong.zhang 已提交
150
                    $.alert.confirm("确定删除该" + options.modalName + "信息?", function () {
Y
yadong.zhang 已提交
151 152 153 154 155 156
                        $.ajax({
                            type: "post",
                            url: options.removeUrl,
                            traditional: true,
                            data: {'ids': ids},
                            success: function (json) {
Y
yadong.zhang 已提交
157
                                $.alert.ajaxSuccess(json);
Y
yadong.zhang 已提交
158 159
                                $.tableUtil.refresh();
                            },
160 161 162
                            error: function (error) {
                                console.error(error);
                            }
Y
yadong.zhang 已提交
163 164 165 166 167 168 169 170 171 172
                        });
                    }, function () {

                    }, 5000);
                }

                /* 批量删除用户 */
                $("#btn_delete_ids").click(function () {
                    var selectedId = getSelectedId();
                    if (!selectedId || selectedId == '[]' || selectedId.length == 0) {
Y
yadong.zhang 已提交
173
                        $.alert.error("请至少选择一条记录");
Y
yadong.zhang 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
                        return;
                    }
                    remove(selectedId);
                });

                /* 删除 */
                $('#tablelist').on('click', '.btn-remove', function () {
                    var $this = $(this);
                    var userId = $this.attr("data-id");
                    remove(userId);
                });
            }
        }
    });
})(jQuery);

function bindSaveInfoEvent(url) {
191
    $(".addOrUpdateBtn").unbind('click').click(function () {
Y
yadong.zhang 已提交
192 193 194 195 196 197
        if (validator.checkAll($("#addOrUpdateForm"))) {
            $.ajax({
                type: "post",
                url: url,
                data: $("#addOrUpdateForm").serialize(),
                success: function (json) {
Y
yadong.zhang 已提交
198
                    $.alert.ajaxSuccess(json);
Y
yadong.zhang 已提交
199 200 201
                    $("#addOrUpdateModal").modal('hide');
                    $.tableUtil.refresh();
                },
Y
yadong.zhang 已提交
202
                error: $.alert.ajaxError
Y
yadong.zhang 已提交
203 204 205 206 207 208
            });
        }
    })
}

function resetForm(info) {
209 210 211 212
    var $combox = $("#addOrUpdateModal form select[target=combox]");
    if($combox && $combox[0]) {
        zhyd.combox.init();
    }
Y
yadong.zhang 已提交
213 214 215 216 217 218
    $("#addOrUpdateModal form input,#addOrUpdateModal form select,#addOrUpdateModal form textarea").each(function () {
        var $this = $(this);
        clearText($this, this.type, info);
    });
}

219
function clearText($this, type, info) {
Y
yadong.zhang 已提交
220
    var $div = $this.parents(".item");
Y
yadong.zhang 已提交
221 222
    if ($div && $div.hasClass("bad")) {
        $div.removeClass("bad");
Y
yadong.zhang 已提交
223 224 225 226 227 228
        $div.find("div.alert").remove();
    }
    if (info) {
        var thisName = $this.attr("name");
        var thisValue = info[thisName];
        if (type == 'radio') {
229
            var _typeof = (typeof thisValue);
230
            if (_typeof == "boolean" || _typeof == "number") {
231 232 233 234 235
                $this.iCheck(((thisValue && 1 == $this.val()) || (!thisValue && 0 == $this.val())) ? 'check' : 'uncheck')
            } else if (_typeof == "string") {
                $this.iCheck(((thisValue == '1' && 1 == $this.val()) || (thisValue != '1' && 0 == $this.val())) ? 'check' : 'uncheck')
            }

Y
yadong.zhang 已提交
236
        } else if (type.startsWith('select')) {
237
            if (thisValue == 'true' || thisValue == true) {
Y
yadong.zhang 已提交
238
                thisValue = 1;
239
            } else if (thisValue == 'false' || thisValue == false) {
Y
yadong.zhang 已提交
240
                thisValue = 0;
Y
yadong.zhang 已提交
241
            }
Y
yadong.zhang 已提交
242 243
            $this.val(thisValue);
        } else {
244
            if (type != 'password') {
245 246 247 248
                $this.val(thisValue);
            } else {
                $this.val('');
            }
Y
yadong.zhang 已提交
249 250
        }
    } else {
Y
yadong.zhang 已提交
251
        if (type === 'radio' || type === 'checkbox') {
Y
yadong.zhang 已提交
252
            $this.iCheck('uncheck');
253
        } else {
Y
yadong.zhang 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            $this.val('');
        }
    }
}

/**
 * 获取选中的记录ID
 * @returns {Array}
 */
function getSelectedId() {
    var selectedJson = $("#tablelist").bootstrapTable('getAllSelections');
    var ids = [];
    $.each(selectedJson, function (i) {
        ids.push(selectedJson[i].id);
    });
    return ids;
}

/**
 * 获取选中的记录
 * @returns {*|jQuery}
 */
function getSelectedObj() {
Y
yadong.zhang 已提交
277
    return $("#tablelist").bootstrapTable('getAllSelections');
Y
yadong.zhang 已提交
278
}