bootstrap table 重構 queryParams#
queryParams:function(params){
let filter = JSON.parse(params.filter);
let op = JSON.parse(params.op);
//重構搜索條件
filter['game.game_mode'] = 0;
filter['game.play_mode'] = 0;
op['game.game_mode'] = '=';
op['game.play_mode'] = '=';
params.filter = JSON.stringify(filter);
params.op = JSON.stringify(op);
console.log(params);
return params;
}
table 頁腳統計和按鈕複製到剪貼板等小功能#
- 給 Table.api.init 內增加 showFooter 配置,開啟頁腳
- columns {field} 增加 footerFormatter,作為統計表頭
- 需要統計的列 添加代碼 footerFormatter(rows){
return sumFormatter(rows,this.field)
} - 添加 js 方法和監聽滾動條代碼 (如果有滾動條可使頁腳跟隨滾動條滾動)
- 進階 通過監聽 checkbox, 頁面只統計勾選的數據,用到 checkData 和 table.bootstrapTable ('resetFooter')
define(['jquery', 'bootstrap', 'backend', 'table', 'form','layui'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格參數配置
Table.api.init({
showFooter:true, //此處配置項有效
extend: {}
});
var table = $("#table");
//修改彈出框大小
$('.btn-edit').data('area',["75%","75%"])
// 初始化表格
table.bootstrapTable({
columns: [
[
{checkbox: true},
{field: 'id', title: __('Id')},
{field: 'operate', title: __('Operate'), table: table,
buttons: [
{
name: 'pwd',
text: __('Copy Account'),
icon: 'fa fa-copy',
classname: 'btn btn-xs btn-primary btn-ajax',
url: 'auth/admin/pwd?u={accname}',
success: function (data, ret) {
let info = '後台地址:' + data.url + '\n帳號:' + data.username + '\n密碼:' + data.pass;
//使用方法
var ct =new copy_txt();
ct.copy(info);//把"xxx"複製到粘貼板
},
error: function (data, ret) {
console.log(data, ret);
Layer.alert(ret.msg);
return false;
},
visible: function (row) {
//返回true時按鈕顯示,返回false隱藏
if (row.account){
return true;
}else{
return false;
}
}
}
], events: Table.api.events.operate, formatter: Table.api.formatter.operate},
{field: 'userName', title: __('Nickname'), operate: 'LIKE',footerFormatter:totalTextFormatter},
{field: 'balance', title: __('Balance'),operate:false,operate:false,footerFormatter:function(rows){
return sumFormatter(rows,this.field)
}},
{field: 'frozen', title: __('Frozen Balance'),operate:false,operate:false,footerFormatter:function(rows){
return sumFormatter(rows,this.field)
}},
]
]
});
//監聽checkbox
table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table post-body.bs.table', function (e) {
checkData = Table.api.selecteddata(table);
table.bootstrapTable('resetFooter');
})
//可以隱藏某一個列
if (!Config.show) {
table.bootstrapTable('hideColumn','statmidday.platformFee');
table.bootstrapTable('hideColumn','platformFee');
table.bootstrapTable('hideColumn','frozenPlatformFee');
}
//修改表格內的按鈕
table.on('post-body.bs.table',function () {
$('.btn-editone').data('area',["75%","75%"])
})
var copy_txt=function(){//無組件複製到剪貼板
var _this =this;
this.copy=function(txt){
$("#input_copy_txt_to_board").val(txt);//賦值
$("#input_copy_txt_to_board").removeClass("hide");//顯示
$("#input_copy_txt_to_board").focus();//取得焦點
$("#input_copy_txt_to_board").select();//選擇
document.execCommand("Copy");
$("#input_copy_txt_to_board").addClass("hide");//隱藏
}
//-----------
let html ='<textarea class="hide" id="input_copy_txt_to_board" /></textarea>';//添加一個隱藏的元素 可換行
//let html ='<input type class="hide" id="input_copy_txt_to_board" value="" />';//添加一個隱藏的元素
$("body").append(html);
}
//監聽滾動條
$(".fixed-table-body").on("scroll",function(){
var sl=this.scrollLeft;
$(this).next()[0].scrollLeft = sl;
})
// 為表格綁定事件
Table.api.bindevent(table);
},
//頁面彈出編輯框,提交修改後台刷新當前頁面
keepamount: function () {
Form.api.bindevent("form[role='form']", function(res){
parent.location.reload();//這裡刷新父頁面,可以換其他代碼
});
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
}
}
};
return Controller;
});
//頁腳統計js begin
function totalTextFormatter() {
return '總計:';
}
let checkData = [];
function sumFormatter(rows,value,format= false) {
if (checkData.length) {
rows = checkData;
}
var sum = 0;
for (var i=0;i<rows.length;i++) {
sum += Number(rows[i][value])
}
let result = 0;
if (format){
result = sum.toString();
}else {
result = toDecimal2(sum)
}
return result;
}
function toDecimal2(x) {
var f = Math.round(x * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
//頁腳統計js end
進階 根據 checkbox 勾選,只頁腳統計,勾選內容#
通過 checkData 和 table.bootstrapTable ('resetFooter'); 實現
//監聽checkbox
table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table post-body.bs.table', function (e) {
checkData = Table.api.selecteddata(table);
table.bootstrapTable('resetFooter');
})
let checkData = [];
function sumFormatter(rows,value,format= false) {
if (checkData.length) {
rows = checkData;
}
var sum = 0;
for (var i=0;i<rows.length;i++) {
sum += Number(rows[i][value])
}
let result = 0;
if (format){
result = sum.toString();
}else {
result = toDecimal2(sum)
}
return result;
}
注意
public/assets/libs/bootstrap-table/dist/bootstrap-table.js 中的 resetFooter 默認不開放
需要修改代碼 大致 3016 行,把 resetFooter ,追加寫在末尾
var allowedMethods = [... 省略其他方法名,'resetFooter']
改好後需要壓縮 js, 並且複製到同目錄下的 bootstrap-table.min.js 中
最後執行
php think min -m backend -r all
table 頁腳 bug - 頁腳統計與列無法對齊#
看起來就像頁腳,每個單元格都多了一個像素,整的對不齊
後來我就找到這個頁腳生成的 js, 做了些修改
public/assets/libs/bootstrap-table/dist/bootstrap-table.js 差不多在 2288 行
下面代碼 注釋的就是原來的 上面那行是我修改的
$footerTd.eq(i).find(".fht-cell").width($this[0].getBoundingClientRect().width - 1)
//$footerTd.eq(i).find(".fht-cell").width($this.innerWidth())
改好後需要壓縮 複製到同目錄下的 bootstrap-table.min.js
在線壓縮工具
所以最後還要執行
php think min -m backend -r all
table 頁腳 bug - 頁腳和固定列 css 問題#
頁腳和固定列同時開啟時,固定列會多一塊,可以用 css 樣式去掉
<style>
.fixed-table-container .fixed-columns {
height: calc(100% - 116px) !important;
}
</style>
#table開啟固定列
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
searchFormVisible: true,
toolbar: '#toolbar',
fixedColumns: true, //開啟固定列
fixedNumber: 2, //左邊列固定
#省略..
})
public/assets/libs/bootstrap-table/dist/bootstrap-table.js#
BootstrapTable.prototype.fitFooter = function () {
//....
//todo $this.innerWidth() 這個版本js無法獲取精度數字 改好後壓縮下 bootstrap-table.min.js
this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
var $this = $(this);
$footerTd.eq(i).find(".fht-cell").width($this[0].getBoundingClientRect().width - 1)
//$footerTd.eq(i).find(".fht-cell").width($this.innerWidth())
});
};
tab 分頁 多表 table#
<div class="panel panel-default panel-intro">
{:build_heading()}
<ul class="nav nav-tabs main">
{foreach name="typeList" item="vo" index="i"}
<li {if $i==1}class="active"{/if}><a href="#{$key}" data-toggle="tab">{$vo}</a></li>
{/foreach}
</ul>
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
{:build_toolbar('refresh,add,delete')}
</div>
<table id="table" class="table table-striped table-bordered table-hover"
data-operate-edit=false
width="100%">
</table>
</div>
</div>
<div class="tab-pane fade" id="two">
<div class="widget-body no-padding">
<div id="toolbar2" class="toolbar">
{:build_toolbar('refresh,add,delete')}
</div>
<table id="table2" class="table table-striped table-bordered table-hover"
data-operate-edit=false
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
對應 js
index: function () {
Table.api.init();
//綁定事件
$('.main a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var panel = $($(this).attr("href"));
console.log(panel)
if (panel.size() > 0) {
Controller.table[panel.attr("id")].call(this);
$(this).on('click', function (e) {
console.log(1)
$($(this).attr("href")).find(".btn-refresh").trigger("click");
});
}
//移除綁定的事件
$(this).unbind('shown.bs.tab');
});
//必須默認觸發shown.bs.tab事件
$('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
},
table: {
one: function () {
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: '',
extend: {
index_url: '',
add_url: '',
del_url: '',
table: '',
},
pk: 'id',
sortName: 'weigh',
toolbar:'#toolbar',
columns: [
[
{checkbox: true},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
],
sidePagination: "client", //客戶端分頁
});
// 為表格綁定事件
Table.api.bindevent(table);
},
two: function () {
var table = $("#table2");
// 初始化表格
table.bootstrapTable({
url: '',
extend: {
index_url: '',
add_url: '',
del_url: '',
table: '',
},
pk: 'id',
sortName: 'weigh',
toolbar:'#toolbar2',
columns: [
[
{checkbox: true},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
],
sidePagination: "client", //客戶端分頁
});
// 為表格綁定事件
Table.api.bindevent(table);
},
},
btn-group 按鈕組 dropdown#
當按鈕太多時,把幾個按鈕合併到按鈕組中
buttons: [
{
name: '',
text: '',
title: '',
classname: 'btn btn-xs btn-info btn-dialog',
icon: 'fa fa-list-alt',
url: '',
extend: 'data-area=\'["650px", "450px"]\'',
dropdown:__('Operate'), //需要放一起的按鈕都加上 dropdown
callback: function (data) {
},
visible: function (row) {
//返回true時按鈕顯示,返回false隱藏
return true;
}
}
]
由於 btn-group 按鈕組 顯示的不太友好 自己瞎搞調整了下 css 樣式
.dropdown-menu.pull-right {
right: auto;
top: auto;
margin-top: 24px;
}
.dropdown-menu > li > a {
text-align: left;
}
.btn-group {
position: inherit;
display: inline-flex;
}
btn-group 多個按鈕組中間有個逗號#
require-table.js html.unshift (dropdownHtml) 修改 html.unshift (dropdownHtml.join (' '))
if (!$.isEmptyObject(dropdowns)) {
var dropdownHtml = [];
$.each(dropdowns, function (i, j) {
dropdownHtml.push('<div class="btn-group"><button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">' + i + '</button><button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right"><li>' + j.join('</li><li>') + '</li></ul></div>');
});
html.unshift(dropdownHtml.join(' '));
}
return html.join(' ');
表格顯示列,全選與全不選#
index: function () {
// 初始化表格參數配置
var table = $("#table");
table.on('post-common-search.bs.table', function (e, settings, json, xhr) {
$("ul.dropdown-menu", settings.$toolbar).prepend("<li role='menucheckall'><label><input type='checkbox' checked> 全選/反選</label></li>");
$(document).on("click", "ul.dropdown-menu li[role='menucheckall'] input", function (e) {
e.stopPropagation();
var that = settings;
var checked = $(this).prop('checked');
$("ul.dropdown-menu li[role='menuitem'] input").each(function () {
that.toggleColumn($(this).val(), checked, false);
that.trigger('column-switch', $(this).data('field'), checked);
$(this).prop("checked", checked);
});
});
});
// 為表格綁定事件
Table.api.bindevent(table);
}
單日期 day 自定義搜索#
bootstrap table 的搜索樣式 單個日期搜索
參考鏈接
https://ask.fastadmin.net/question/28226.html
[
{field: 'day', title: __('Day'), addclass:'datetimepicker', data: 'data-date-format="YYYYMMDD"'},
]
顯示有 bug
.bootstrap-table .form-commonsearch .form-group {
white-space: normal;
}
bulid_checkboxs 增加全選 / 反選#
bulid_checkboxs 構建的多選框 沒有全選 / 反選
這裡通過在數組開頭增加 ['' => ' 全選 / 反選 ']
bulid_checkboxs ('status []',['' => ' 全選 / 反選 ',... 其他元素])
再配合 js 達成 全選 / 反選的效果
//初始化 checkbox 是否勾選全選/反選
function init(name) {
let elem = $('input[name="' + name + '"]');
//當前列 checkbox 除了全選/反選的 元素數量
let len = elem.length - 1;
let chk = $('input[name="' + name + '"]:checked');
let chklen = chk.length;
//排除全選
if (elem.first().prop("checked")) {
chklen = chk.length - 1;
}
if (len == chklen && chklen != 0){
elem.first().prop("checked",true);
}else {
elem.first().prop("checked",false);
}
}
init('status');
$(":checkbox").on('click',function(){
//獲取當前 name
let name = $(this).attr('name');
let elem = $('input[name="' + name + '"]');
//當前列 checkbox 除了全選/反選的 元素數量
let len = elem.length - 1;
//判斷全選/反選
let checked = $(this).prop('checked');
let key = $(this).val();
if (key == '') {
if (checked) {
elem.prop("checked",true);
} else {
elem.prop("checked",false);
}
}
//如果有一個未選中則取消全選按鈕的選中狀態/全都選擇設置全選按鈕為選中狀態
let chk = $('input[name="' + name + '"]:checked');
let chklen = chk.length;
//排除全選
if (elem.first().prop("checked")) {
chklen = chk.length - 1;
}
if (len == chklen && chklen != 0){
elem.first().prop("checked",true);
}else {
elem.first().prop("checked",false);
}
})
如果不選 checkbox ,php 後台接收參數不是 [] 而是 [0 => '']
可用 array_filter 過濾
$status = array_filter($status);
實用的表格列表字段顯示優化,採用 cookie 記憶隱藏字段功能。#
define(['jquery', 'bootstrap', 'backend', 'table', 'form','cookie'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格參數配置
var table = $("#table");
// 選擇隱藏字段事件,使用cookie存入
table.on('column-switch.bs.table', function (e, json) {
var myColumns = [];
$.each(table.bootstrapTable('getHiddenColumns'), function (i, item) {
myColumns.push(item.field);
});
let cookieName = 'fa_{%table%}' //fa_\{%table%\} 反斜杆去掉
$.cookie(cookieName, JSON.stringify(myColumns), {expires: 365, path: '/'});
});
if ($.cookie(cookieName)) {
//讀取cookie隱藏字段
$.each(JSON.parse($.cookie(cookieName)), function (i, item) {
table.bootstrapTable('hideColumn', item);
});
}
// 為表格綁定事件
Table.api.bindevent(table);
}
}
})
記錄當前窗體內的確認框觸發#
$('.btn-release').on('click',function () {
event.preventDefault();
Layer.confirm(__('Confirm Release?'), {
title: __('Confirm Release?'),
}, function (index) {
Fast.api.ajax({
url: "",
}, function (data) {
Layer.closeAll('dialog'); //關閉確認框
Fast.api.close(1); //關閉窗體並回傳數據
parent.$(".btn-refresh").trigger("click"); //觸發窗體的父頁面刷新
},function () {
});
}, function (index) {
});
});
自定義搜索 (下拉框搜索)#
fastAdmin 有個開發實例的插件,包括一些實用的技巧,如下
var table = $("#table");
//在普通搜索渲染後
table.on('post-common-search.bs.table', function (event, table) {
var form = $("form", table.$commonsearch);
$("input[name='bankID']", form).addClass("selectpage").data("source", "bank/bank/index").data("primaryKey", "id").data("field", "account").data("orderBy", "id desc");
Form.events.cxselect(form);
Form.events.selectpage(form);
});
let col = [
{checkbox: true},
{field: 'id', title: __('Id')},
{field: 'bankID', title: __('Account'),visible: false},
{field: 'bank.account', title: __('Account'), operate: false},
]
固定表格高度#
<table data-height="500"></table>
或
table.bootstrapTable({
...
height: 500,
...
})
添加表格顯示列的全選反選#
//添加表格顯示列的全選反選
table.on('post-common-search.bs.table', function (e, settings, json, xhr) {
$("ul.dropdown-menu", settings.$toolbar).prepend("<li role='menucheckall'><label><input type='checkbox' checked> 全選/反選</label></li>");
$(document).on("click", "ul.dropdown-menu li[role='menucheckall'] input", function (e) {
e.stopPropagation();
var that = settings;
var checked = $(this).prop('checked');
$("ul.dropdown-menu li[role='menuitem'] input").each(function () {
that.toggleColumn($(this).val(), checked, false);
that.trigger('column-switch', $(this).data('field'), checked);
$(this).prop("checked", checked);
});
});
});