amber

amber

FastAdmin Personal Records - bootstrap table

Reconstructing queryParams for bootstrap table#

queryParams:function(params){
   let filter = JSON.parse(params.filter);
   let op = JSON.parse(params.op);
   
   // Reconstruct search conditions
   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;
}
  1. Add showFooter configuration to Table.api.init to enable footer
  2. Add footerFormatter to columns {field} as the statistical header
  3. For columns that need statistics, add code footerFormatter(rows){
    return sumFormatter(rows,this.field)
    }
  4. Add js methods and scroll bar listener code (if there is a scroll bar, make the footer follow the scroll bar)
  5. Advanced: By listening to the checkbox, the page only counts the checked data, using checkData and table.bootstrapTable('resetFooter')
define(['jquery', 'bootstrap', 'backend', 'table', 'form','layui'], function ($, undefined, Backend, Table, Form) {
    
    var Controller = {
        index: function () {
            // Initialize table parameter configuration
            Table.api.init({
                showFooter:true,   // This configuration is effective
                extend: {}
            });

            var table = $("#table");

            // Modify popup size
            $('.btn-edit').data('area',["75%","75%"])

            // Initialize table
            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 = 'Backend address:' + data.url + '\nAccount:' + data.username + '\nPassword:' +  data.pass;
                                   // Usage method
                                   var ct =new copy_txt();
                                   ct.copy(info);// Copy "xxx" to clipboard
                                },
                                error: function (data, ret) {
                                   console.log(data, ret);
                                   Layer.alert(ret.msg);
                                   return false;
                                },
                                visible: function (row) {
                                   // Return true to show button, return false to hide
                                   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,footerFormatter:function(rows){
                                return sumFormatter(rows,this.field)
                            }},
                        {field: 'frozen', title: __('Frozen Balance'),operate:false,footerFormatter:function(rows){
                                return sumFormatter(rows,this.field)
                            }},
                    ]
                ]
            });

            // Listen to 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');
            })

            // Can hide a certain column
            if (!Config.show) {
                table.bootstrapTable('hideColumn','statmidday.platformFee');
                table.bootstrapTable('hideColumn','platformFee');
                table.bootstrapTable('hideColumn','frozenPlatformFee');
            }

            // Modify buttons in the table
            table.on('post-body.bs.table',function () {
                $('.btn-editone').data('area',["75%","75%"])
            })

            var copy_txt=function(){// Copy to clipboard without component
                var _this =this;
                this.copy=function(txt){

                    $("#input_copy_txt_to_board").val(txt);// Assign value
                    $("#input_copy_txt_to_board").removeClass("hide");// Show
                    $("#input_copy_txt_to_board").focus();// Focus
                    $("#input_copy_txt_to_board").select();// Select
                    document.execCommand("Copy");
                    $("#input_copy_txt_to_board").addClass("hide");// Hide
                }

                //-----------
                let html ='<textarea class="hide" id="input_copy_txt_to_board" /></textarea>';// Add a hidden element that can wrap
                //let html ='<input type class="hide" id="input_copy_txt_to_board" value="" />';// Add a hidden element
                $("body").append(html);
            }

            // Listen to scroll bar
            $(".fixed-table-body").on("scroll",function(){
                var sl=this.scrollLeft;
                $(this).next()[0].scrollLeft = sl;
            })

            // Bind events to the table
            Table.api.bindevent(table);
        },
        // Popup edit box on the page, submit modification and refresh the current page
        keepamount: function () {

            Form.api.bindevent("form[role='form']", function(res){
                parent.location.reload();// Refresh parent page here, can change to other code
            });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});

// Footer statistics js begin
function totalTextFormatter() {
    return 'Total:';
}
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;
}
// Footer statistics js end

Achieved through checkData and table.bootstrapTable('resetFooter');


// Listen to 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;
}

Note
The resetFooter in public/assets/libs/bootstrap-table/dist/bootstrap-table.js is not enabled by default
You need to modify the code around line 3016, append resetFooter at the end
var allowedMethods = [ ...other method names,'resetFooter']
After fixing, compress the js, and copy it to bootstrap-table.min.js in the same directory
Finally execute
php think min -m backend -r all

It looks like the footer, each cell has an extra pixel, making it misaligned
Later I found the js that generates this footer and made some modifications
Around line 2288 in public/assets/libs/bootstrap-table/dist/bootstrap-table.js
The code below comments out the original, the above line is my modification

$footerTd.eq(i).find(".fht-cell").width($this[0].getBoundingClientRect().width - 1)
//$footerTd.eq(i).find(".fht-cell").width($this.innerWidth())

After fixing, compress and copy to bootstrap-table.min.js in the same directory
Online compression tool
So finally execute
php think min -m backend -r all

When both footer and fixed columns are enabled, the fixed column will have an extra block, which can be removed with css styles

<style>
.fixed-table-container .fixed-columns {
        height: calc(100% - 116px) !important;
    }
</style>

# Enable fixed columns for the table
table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url,
                    pk: 'id',
                    sortName: 'id',
                    searchFormVisible: true,
                    toolbar: '#toolbar',
                    fixedColumns: true, // Enable fixed columns
                    fixedNumber: 2,     // Fixed columns on the left
                    # omitted..
                    })

public/assets/libs/bootstrap-table/dist/bootstrap-table.js#

BootstrapTable.prototype.fitFooter = function () {
        //....
        //todo $this.innerWidth() This version of js cannot get precise numbers, after fixing compress 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 pagination multiple tables#

<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>

Corresponding js

index: function () {
            Table.api.init();
            // Bind events
            $('.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");
                    });
                }
                // Remove bound events
                $(this).unbind('shown.bs.tab');
            });

            // Must trigger shown.bs.tab event by default
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
        },
        table: {
            one: function () {

                var table = $("#table");

                // Initialize 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", // Client-side pagination
                });

                // Bind events to the table
                Table.api.bindevent(table);
            },
            two: function () {

                var table = $("#table2");

                // Initialize table
                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", // Client-side pagination
                });

                // Bind events to the table
                Table.api.bindevent(table);
            },
        },

btn-group button group dropdown#

When there are too many buttons, merge several buttons into a button group

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'), // Add dropdown to buttons that need to be grouped
        callback: function (data) {
        },
        visible: function (row) {
            // Return true to show button, return false to hide
            return true;
        }
    }
]

Since the btn-group button group display is not very friendly, I adjusted the css styles

    .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;
    }

3-1

btn-group multiple button groups with a comma in between#

require-table.js html.unshift(dropdownHtml) Change to 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(' ');

Table display column, select all and deselect all#

Reference link
https://ask.fastadmin.net/question/9304.html

index: function () {
    // Initialize table parameter configuration
    
    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> Select All/Toggle</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);
            });
        });
    });
            // Bind events to the table
    Table.api.bindevent(table);
}

Bootstrap table's search style for single date search
Reference link
https://ask.fastadmin.net/question/28226.html

[
    {field: 'day', title: __('Day'), addclass:'datetimepicker', data: 'data-date-format="YYYYMMDD"'},
]

Display bug

.bootstrap-table .form-commonsearch .form-group {
    white-space: normal;
}

bulid_checkboxs add select all/toggle#

bulid_checkboxs constructed multiple checkboxes do not have select all/toggle
Here, add ['' => 'Select All/Toggle'] at the beginning of the array
bulid_checkboxs('status[]',['' => 'Select All/Toggle',...other elements])
Then use js to achieve the select all/toggle effect


            // Initialize checkbox whether to check select all/toggle
            function init(name) {
                let elem = $('input[name="' + name + '"]');
                // Number of elements in the current column checkbox excluding select all/toggle
                let len = elem.length - 1;
                let chk = $('input[name="' + name + '"]:checked');
                let chklen = chk.length;
                // Exclude select all
                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(){
                // Get current name
                let name = $(this).attr('name');
                let elem = $('input[name="' + name + '"]');
                // Number of elements in the current column checkbox excluding select all/toggle
                let len = elem.length - 1;

                // Determine select all/toggle
                let checked = $(this).prop('checked');
                let key = $(this).val();
                if (key == '') {
                    if (checked) {
                        elem.prop("checked",true);
                    } else {
                        elem.prop("checked",false);
                    }
                }

                // If one is not selected, cancel the select all button's selected state / if all are selected, set the select all button to selected
                let chk = $('input[name="' + name + '"]:checked');
                let chklen = chk.length;
                // Exclude select all
                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);
                }
            })

If the checkbox is not selected, the php backend receives the parameter as not [] but [0 => '']
You can use array_filter to filter
$status = array_filter($status);

Reference link
https://ask.fastadmin.net/article/9464.html

define(['jquery', 'bootstrap', 'backend', 'table', 'form','cookie'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // Initialize table parameter configuration
    
            var table = $("#table");
    
            // Select hidden field event, stored in 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%\} Remove backslash
                $.cookie(cookieName, JSON.stringify(myColumns), {expires: 365, path: '/'});
            });
            if ($.cookie(cookieName)) {
                // Read cookie hidden fields
                $.each(JSON.parse($.cookie(cookieName)), function (i, item) {
                    table.bootstrapTable('hideColumn', item);
                });
            }
            // Bind events to the table
            Table.api.bindevent(table);
        }
    }
})

Record the confirmation box trigger in the current window#

            $('.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'); // Close confirmation box
                        Fast.api.close(1); // Close window and return data
                        parent.$(".btn-refresh").trigger("click"); // Trigger refresh of parent page
                    },function () {
                    });
                }, function (index) {

                });
            });

FastAdmin has a development instance plugin that includes some practical tips, as follows

            var table = $("#table");

            // After normal search rendering
            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},
            ]

Fixed table height#

<table data-height="500"></table>

or

 table.bootstrapTable({
    ...
    height: 500,
    ...
})

Add select all toggle for table display columns#

            // Add select all toggle for table display columns
            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> Select All/Toggle</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);
                    });
                });
            });
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.