浏览代码

Fix: A table with a fixed header clears the filtercontrol fields after filter runs

Fix #905 , Fix:
Dennis Hernández 10 年之前
父节点
当前提交
620b567b28

+ 2 - 2
src/extensions/filter-control/README.md

@@ -1,6 +1,6 @@
 # Table Filter Control
 
-Use Plugin: [bootstrap-table-filter-control](https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/filter-control)
+Use Plugin: [bootstrap-table-filter-control](https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/filter-control) </br>
 Dependence if you use the datepicker option: [bootstrap-datepicker](https://github.com/eternicode/bootstrap-datepicker) v1.4.0
 
 ## Usage
@@ -22,7 +22,7 @@ Dependence if you use the datepicker option: [bootstrap-datepicker](https://gith
 ### filterControl
 
 * type: String
-* description: Set `input`: show an input control, `select`: show a select control, 'datepicker': show a datepicker control.
+* description: Set `input`: show an input control, `select`: show a select control, `datepicker`: show a datepicker control.
 * default: `undefined`
 
 ### filterDatepickerOptions

+ 88 - 37
src/extensions/filter-control/bootstrap-table-filter-control.js

@@ -62,9 +62,7 @@
     };
 
     var addValueToSelectControl = function (selectControl, value, text) {
-        var isValidToAdd = existsValueInSelectControl(selectControl, value);
-
-        if (isValidToAdd) {
+        if (existsValueInSelectControl(selectControl, value)) {
             selectControl.append($("<option></option>")
                 .attr("value", value)
                 .text(text));
@@ -86,42 +84,30 @@
         return true;
     };
 
-    $.extend($.fn.bootstrapTable.defaults, {
-        filterControl: false,
-        onColumnSearch: function (field, text) {
-            return false;
-        }
-    });
-
-    $.extend($.fn.bootstrapTable.COLUMN_DEFAULTS, {
-        filterControl: undefined,
-        filterData: undefined,
-        filterDatepickerOptions: undefined
-    });
-
-    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
-        'column-search.bs.table': 'onColumnSearch'
-    });
-
-    var BootstrapTable = $.fn.bootstrapTable.Constructor,
-        _initHeader = BootstrapTable.prototype.initHeader,
-        _initBody = BootstrapTable.prototype.initBody,
-        _initSearch = BootstrapTable.prototype.initSearch;
+    var fixHeaderCSS = function (that) {
+        that.$tableHeader.css('height', '77px');
+    };
 
-    BootstrapTable.prototype.initHeader = function () {
-        _initHeader.apply(this, Array.prototype.slice.apply(arguments));
+    var copyValues = function (that) {
+        that.options.values = [];
+        that.$tableHeader.find('table select, table input').each(function () {
+            that.options.values.push($(this).val());
+        });
+    };
 
-        if (!this.options.filterControl) {
-            return;
-        }
+    var setValues = function(that) {
+        that.$tableHeader.find('table select, table input').each(function (index, ele) {
+            $(this).val(that.options.values[index]);
+        });
+    };
 
+    var createControls = function (that, header) {
         var addedFilterControl = false,
-            that = this,
             isVisible,
             html,
             timeoutId = 0;
 
-        $.each(this.options.columns, function (i, column) {
+        $.each(that.options.columns, function (i, column) {
             isVisible = 'hidden';
             html = [];
 
@@ -153,7 +139,7 @@
                 }
             }
 
-            that.$header.find(sprintf('.th-inner:eq("%s")', i)).next().append(html.join(''));
+            header.find(sprintf('.th-inner:eq("%s")', i)).next().append(html.join(''));
             if (column.filterData !== undefined && column.filterData.toLowerCase() !== 'column') {
                 var filterDataType = column.filterData.substring(0, 3);
                 var filterDataSource = column.filterData.substring(4, column.filterData.length);
@@ -183,14 +169,14 @@
         });
 
         if (addedFilterControl) {
-            this.$header.off('keyup', 'input').on('keyup', 'input', function (event) {
+            header.off('keyup', 'input').on('keyup', 'input', function (event) {
                 clearTimeout(timeoutId);
                 timeoutId = setTimeout(function () {
                     that.onColumnSearch(event);
                 }, that.options.searchTimeOut);
             });
 
-            this.$header.off('change', 'select').on('change', 'select', function (event) {
+            header.off('change', 'select').on('change', 'select', function (event) {
                 clearTimeout(timeoutId);
                 timeoutId = setTimeout(function () {
                     that.onColumnSearch(event);
@@ -199,22 +185,86 @@
 
             var datepickers = that.$header.find('.date-filter-control');
             if (datepickers.length > 0) {
-                $.each(this.options.columns, function (i, column) {
+                $.each(that.options.columns, function (i, column) {
                     if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'datepicker') {
                         column.filterDatepickerOptions = $.extend(column.filterDatepickerOptions, {
                             calendarWeeks: true
                         });
 
-                        that.$header.find('.date-filter-control.' + column.field).datepicker(column.filterDatepickerOptions)
+                        header.find('.date-filter-control.' + column.field).datepicker(column.filterDatepickerOptions)
                             .on('changeDate', function (e) {
+                                //Fired the keyup event
                                 $(e.currentTarget).keyup();
                             });
                     }
                 });
             }
         } else {
-            this.$header.find('.filterControl').hide();
+            header.find('.filterControl').hide();
+        }
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, {
+        filterControl: false,
+        onColumnSearch: function (field, text) {
+            return false;
+        },
+        values: [] //internal variables
+    });
+
+    $.extend($.fn.bootstrapTable.COLUMN_DEFAULTS, {
+        filterControl: undefined,
+        filterData: undefined,
+        filterDatepickerOptions: undefined
+    });
+
+    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
+        'column-search.bs.table': 'onColumnSearch'
+    });
+
+    var BootstrapTable = $.fn.bootstrapTable.Constructor,
+        _init = BootstrapTable.prototype.init,
+        _initHeader = BootstrapTable.prototype.initHeader,
+        _initBody = BootstrapTable.prototype.initBody,
+        _initSearch = BootstrapTable.prototype.initSearch;
+
+    BootstrapTable.prototype.init = function () {
+        //Make sure that the filtercontrol option is set
+        if (this.options.filterControl) {
+            var that = this;
+            this.$el.on('reset-view.bs.table', function () {
+
+                //Create controls on $tableHeader if the height is set
+                if (!that.options.height) {
+                    return;
+                }
+
+                //Avoid recreate the controls
+                if (that.$tableHeader.find('select').length > 0 || that.$tableHeader.find('input').length > 0) {
+                    return;
+                }
+
+                createControls(that, that.$tableHeader);
+            }).on('post-header.bs.table', function () {
+                setValues(that);
+            });
+
+            this.$el.on('post-body.bs.table', function () {
+                if (that.options.height) {
+                    fixHeaderCSS(that);
+                }
+            });
+        }
+        _init.apply(this, Array.prototype.slice.apply(arguments));
+    };
+
+    BootstrapTable.prototype.initHeader = function () {
+        _initHeader.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.filterControl) {
+            return;
         }
+        createControls(this, this.$header);
     };
 
     BootstrapTable.prototype.initBody = function () {
@@ -282,6 +332,7 @@
     };
 
     BootstrapTable.prototype.onColumnSearch = function (event) {
+        copyValues(this);
         var text = $.trim($(event.currentTarget).val());
         var $field = $(event.currentTarget).parent().parent().parent().data('field')
 

+ 159 - 0
src/extensions/groupby/bootstrap-table-groubby.js

@@ -0,0 +1,159 @@
+/**
+ * @author: Dennis Hernández
+ * @webSite: http://djhvscf.github.io/Blog
+ * @version: v1.0.0
+ */
+
+!function ($) {
+
+    'use strict';
+
+    var sprintf = function (str) {
+        var args = arguments,
+            flag = true,
+            i = 1;
+
+        str = str.replace(/%s/g, function () {
+            var arg = args[i++];
+
+            if (typeof arg === 'undefined') {
+                flag = false;
+                return '';
+            }
+            return arg;
+        });
+        return flag ? str : '';
+    };
+
+    var calculateObjectValue = function (self, name, args, defaultValue) {
+        if (typeof name === 'string') {
+            // support obj.func1.func2
+            var names = name.split('.');
+
+            if (names.length > 1) {
+                name = window;
+                $.each(names, function (i, f) {
+                    name = name[f];
+                });
+            } else {
+                name = window[name];
+            }
+        }
+        if (typeof name === 'object') {
+            return name;
+        }
+        if (typeof name === 'function') {
+            return name.apply(self, args);
+        }
+        return defaultValue;
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, {
+        groupBy: false,
+        groupFields: []
+    });
+
+    var BootstrapTable = $.fn.bootstrapTable.Constructor,
+        _initToolbar = BootstrapTable.prototype.initToolbar;
+
+    BootstrapTable.prototype.initToolbar = function () {
+        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.groupBy) {
+            return;
+        }
+
+        if ($.isEmptyObject(this.options.groupFields)){
+            return;
+        }
+
+        var $keepOpen,
+            html = [],
+            that = this,
+            data = this.getData(),
+            dataClone = data.slice(0);
+
+        html.push(sprintf('<div class="keep-by btn-group" title="%s">',
+            this.options.formatColumns()),
+            '<button type="button" class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">',
+            sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
+            ' <span class="caret"></span>',
+            '</button>',
+            '<ul class="dropdown-menu" role="menu">');
+
+        $.each(this.options.groupFields, function (i, field) {
+            if (that.options.cardView) {
+                return;
+            }
+            var checked = '';
+            html.push(sprintf('<li>' +
+                '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
+                '</li>', field, field, checked, field));
+        });
+        html.push('</ul>',
+            '</div>');
+
+        this.$toolbar.find('.columns').append(html.join(''));
+
+        $keepOpen = this.$toolbar.find('.keep-by');
+
+        $keepOpen.find('li').off('click').on('click', function (event) {
+            event.stopImmediatePropagation();
+        });
+
+        $keepOpen.find('input').off('click').on('click', function () {
+            var $this = $(this),
+                order = 1,
+                index = $.inArray($this.val(), that.header.fields);;
+
+            if (index !== -1 && $this.get(0).checked) {
+                data.sort(function (a,b) {
+                    var aa = a[$this.val()],
+                        bb = b[$this.val()],
+                        value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
+
+                    if (value !== undefined) {
+                        return order * value;
+                    }
+
+                    if (aa === undefined || aa === null) {
+                        aa = '';
+                    }
+
+                    if (bb === undefined || bb === null) {
+                        bb = '';
+                    }
+
+                    if ($.isNumeric(aa) && $.isNumeric(bb)) {
+                        aa = parseFloat(aa);
+                        bb = parseFloat(bb);
+                        if (aa < bb) {
+                            return order * -1;
+                        }
+                        return order;
+                    }
+
+                    if (aa === bb) {
+                        return 0;
+                    }
+
+                    if (typeof aa !== 'string') {
+                        aa = aa.toString();
+                    }
+
+                    if (aa.localeCompare(bb) === -1) {
+                        return order * -1;
+                    }
+
+                    return order;
+                });
+
+                //refresh the data
+                that.load(data);
+            } else {
+                //refresh the data to the original order
+                that.load(dataClone);
+            }
+        });
+    };
+}(jQuery);