Browse Source

Added filter control extension and delete the logic from the main js file

Dennis Hernández 10 years ago
parent
commit
cd7e2e618f

+ 1 - 10
docs/_i18n/en/documentation/column-options.md

@@ -211,14 +211,5 @@ The column options is defined in `jQuery.fn.bootstrapTable.columnDefaults`.
         True to search data for this column.
         </td>
     </tr>
-    <tr>
-        <td>filterControl</td>
-        <td>data-filter-control</td>
-        <td>String</td>
-        <td>undefined</td>
-        <td>
-        Can be use 'input' to add an input control to the column or 'select' to add a select control to the column.
-        </td>
-    </tr>
-    </tbody>
+</tbody>
 </table>

+ 2 - 12
docs/_i18n/es/documentation/column-options.md

@@ -182,8 +182,8 @@ Las propiedades de la columna están definidas en `jQuery.fn.bootstrapTable.colu
         <td>String</td>
         <td>undefined</td>
         <td>Proporcionar una especie-nombre adaptable, no la clase-nombre por defecto en la cabecera, o el nombre del campo
-         de la columna. Por ejemplo, una columna puede mostrar el valor de nombreCampo de "HTML" como
-         "&lt;b&gt;&lt;span style="color:red"&gt;abc&lt;/span&gt;&lt;/b&gt;", pero una nombreCampo para ordenar es el "contenido" con el valor de "abc".
+            de la columna. Por ejemplo, una columna puede mostrar el valor de nombreCampo de "HTML" como
+             "&lt;b&gt;&lt;span style="color:red"&gt;abc&lt;/span&gt;&lt;/b&gt;", pero una nombreCampo para ordenar es el "contenido" con el valor de "abc".
         </td>
     </tr>    
     <tr>
@@ -206,15 +206,5 @@ Las propiedades de la columna están definidas en `jQuery.fn.bootstrapTable.colu
         <td>true</td>
         <td>True para incluir la columna en la búsqueda.</td>
     </tr>
-    <tr>
-        <td>filterControl</td>
-        <td>data-filter-control</td>
-        <td>String</td>
-        <td>undefined</td>
-        <td>
-        Se puede usar 'input' para agregar un input control a la columna o 'select' para agregar una lista
-        a la columna.
-        </td>
-    </tr>
     </tbody>
 </table>

+ 2 - 125
src/bootstrap-table.js

@@ -248,9 +248,6 @@
         onColumnSwitch: function (field, checked) {
             return false;
         },
-        onColumnSearch: function (field, text) {
-            return false;
-        },
         onPageChange: function (number, size) {
             return false;
         },
@@ -332,8 +329,7 @@
         sortName: undefined,
         cellStyle: undefined,
         searchable: true,
-        cardVisible: true,
-        filterControl: undefined // edit, select, todo: date
+        cardVisible: true
     };
 
     BootstrapTable.EVENTS = {
@@ -348,7 +344,6 @@
         'load-success.bs.table': 'onLoadSuccess',
         'load-error.bs.table': 'onLoadError',
         'column-switch.bs.table': 'onColumnSwitch',
-        'column-search.bs.table': 'onColumnSearch',
         'page-change.bs.table': 'onPageChange',
         'search.bs.table': 'onSearch',
         'toggle.bs.table': 'onToggle',
@@ -457,7 +452,6 @@
         var that = this,
             visibleColumns = [],
             html = [],
-            addedFilterControl = false,
             timeoutId = 0;
 
         this.header = {
@@ -481,8 +475,7 @@
                 class_ = sprintf(' class="%s"', column['class']),
                 order = that.options.sortOrder || column.order,
                 searchable = true,
-                unitWidth = 'px',
-                isVisible = 'hidden';
+                unitWidth = 'px';
 
             if (!column.visible) {
                 // Fix #229. Default Sort order is wrong if data-visible="false" is set on the field referenced by data-sort-name.
@@ -554,30 +547,7 @@
             html.push(text);
             html.push('</div>');
             html.push('<div class="fht-cell"></div>');
-
-            html.push('<div style="margin: 0px 2px 2px 2px;" class="filterControl">');
-
-            if (column.filterControl && column.searchable) {
-                addedFilterControl = true;
-                isVisible = 'visible'
-            }
-
-            if (column.filterControl !== undefined) {
-                switch (column.filterControl.toLowerCase()) {
-                    case 'input' :
-                        html.push(sprintf('<input type="text" class="form-control" style="width: 100%; visibility: %s">', isVisible));
-                        break;
-                    case 'select':
-                        html.push(sprintf('<select class="%s form-control" style="width: 100%; visibility: %s"></select>',
-                            column.field, isVisible))
-                        break;
-                }
-            } else {
-                html.push('<div style="height: 34px;"></div>');
-            }
-
             html.push('</div>');
-
             html.push('</th>');
         });
 
@@ -607,24 +577,6 @@
                 var checked = $(this).prop('checked');
                 that[checked ? 'checkAll' : 'uncheckAll']();
             });
-
-        if (addedFilterControl) {
-            this.$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) {
-                clearTimeout(timeoutId);
-                timeoutId = setTimeout(function () {
-                    that.onColumnSearch(event);
-                }, that.options.searchTimeOut);
-            });
-        } else {
-            this.$header.find('.filterControl').hide();
-        }
     };
 
     BootstrapTable.prototype.initFooter = function () {
@@ -902,32 +854,12 @@
         this.trigger('search', text);
     };
 
-    BootstrapTable.prototype.onColumnSearch = function (event, isSelectControl) {
-        var text = $.trim($(event.currentTarget).val());
-        var $field = $(event.currentTarget).parent().parent().data('field')
-
-        if ($.isEmptyObject(this.filterColumnsPartial)) {
-            this.filterColumnsPartial = {};
-        }
-        if (text) {
-            this.filterColumnsPartial[$field] = text;
-        } else {
-            delete this.filterColumnsPartial[$field];
-        }
-
-        this.options.pageNumber = 1;
-        this.onSearch(event);
-        this.updatePagination();
-        this.trigger('column-search', $field, text);
-    };
-
     BootstrapTable.prototype.initSearch = function () {
         var that = this;
 
         if (this.options.sidePagination !== 'server') {
             var s = this.searchText && this.searchText.toLowerCase();
             var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
-            var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
 
             // Check filter
             this.data = f ? $.grep(this.options.data, function (item, i) {
@@ -939,24 +871,6 @@
                 return true;
             }) : this.options.data;
 
-            //Check partial colum filter
-            this.data = fp ? $.grep(this.data, function (item, i) {
-                for (var key in fp) {
-                    var fval = fp[key].toLowerCase();
-                    var value = item[key];
-                    value = calculateObjectValue(that.header,
-                        that.header.formatters[$.inArray(key, that.header.fields)],
-                        [value, item, i], value);
-
-                    if (!($.inArray(key, that.header.fields) !== -1 &&
-                        (typeof value === 'string' || typeof value === 'number') &&
-                        (value + '').toLowerCase().indexOf(fval) !== -1)) {
-                        return false;
-                    }
-                }
-                return true;
-            }) : this.data;
-
             this.data = s ? $.grep(this.data, function (item, i) {
                 for (var key in item) {
                     key = $.isNumeric(key) ? parseInt(key, 10) : key;
@@ -1344,43 +1258,6 @@
                             value,
                             '</td>'].join('');
 
-                    if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'select'
-                        && column.searchable) {
-
-                        var selectControl = $('.' + column.field),
-                            iOpt = 0,
-                            exitsOpt = false,
-                            options;
-                        if (selectControl !== undefined) {
-                            options = selectControl.get(0).options;
-
-                            if (options.length === 0) {
-
-                                //Added the default option
-                                selectControl.append($("<option></option>")
-                                    .attr("value", '')
-                                    .text(''));
-
-                                selectControl.append($("<option></option>")
-                                    .attr("value", value)
-                                    .text(value));
-                            } else {
-                                for (; iOpt < options.length; iOpt++) {
-                                    if (options[iOpt].value === value) {
-                                        exitsOpt = true;
-                                        break;
-                                    }
-                                }
-
-                                if (!exitsOpt) {
-                                    selectControl.append($("<option></option>")
-                                        .attr("value", value)
-                                        .text(value));
-                                }
-                            }
-                        }
-                    }
-
                     // Hide empty data on Card view when smartDisplay is set to true.
                     if (that.options.cardView && that.options.smartDisplay && value === '') {
                         text = '';

+ 31 - 0
src/extensions/filtercontrol/README.md

@@ -0,0 +1,31 @@
+# Table Filter Control
+
+Use Plugin: [bootstrap-table-filtercontrol](https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/filtercontrol)
+
+## Usage
+
+```html
+<script src="extensions/filtercontrol/bootstrap-table-filtercontrol.js"></script>
+```
+
+## Options
+
+### filterControl
+
+* type: Boolean
+* description: Set true to add an `input` or `select` into the column.
+* default: `false`
+
+## Column options
+
+### filterControl
+
+* type: String
+* description: Set `input` or `select` to add one of those element into column.
+* default: `undefined`
+
+## Events
+
+### onColumnSearch(column-search.bs.table)
+
+* Fired when we are searching into the column data

+ 245 - 0
src/extensions/filtercontrol/bootstrap-table-filtercontrol.js

@@ -0,0 +1,245 @@
+/**
+ * @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 getFieldIndex = function (columns, field) {
+        var index = -1;
+
+        $.each(columns, function (i, column) {
+            if (column.field === field) {
+                index = i;
+                return false;
+            }
+            return true;
+        });
+        return index;
+    };
+
+    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, {
+        filterControl: false,
+        onColumnSearch: function (field, text) {
+            return false;
+        }
+    });
+
+    $.extend($.fn.bootstrapTable.COLUMN_DEFAULTS, {
+        filterControl: 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;
+
+    BootstrapTable.prototype.initHeader = function () {
+        _initHeader.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.filterControl) {
+            return;
+        }
+
+        var addedFilterControl = false,
+            that = this,
+            isVisible,
+            html,
+            timeoutId = 0;
+
+        $.each(this.options.columns, function (i, column) {
+            isVisible = 'hidden';
+            html = [];
+
+            if (!column.filterControl) {
+                html.push('<div style="height: 34px;"></div>');
+            } else {
+                html.push('<div style="margin: 0px 2px 2px 2px;" class="filterControl">');
+
+                if (column.filterControl && column.searchable) {
+                    addedFilterControl = true;
+                    isVisible = 'visible'
+                }
+                switch (column.filterControl.toLowerCase()) {
+                    case 'input' :
+                        html.push(sprintf('<input type="text" class="form-control" style="width: 100%; visibility: %s">', isVisible));
+                        break;
+                    case 'select':
+                        html.push(sprintf('<select class="%s form-control" style="width: 100%; visibility: %s"></select>',
+                            column.field, isVisible))
+                        break;
+                }
+            }
+
+            that.$header.find(sprintf('.th-inner:contains("%s")', column.title)).next().append(html.join(''));
+        });
+
+        if (addedFilterControl) {
+            this.$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) {
+                clearTimeout(timeoutId);
+                timeoutId = setTimeout(function () {
+                    that.onColumnSearch(event);
+                }, that.options.searchTimeOut);
+            });
+        } else {
+            this.$header.find('.filterControl').hide();
+        }
+    };
+
+    BootstrapTable.prototype.initBody = function () {
+        _initBody.apply(this, Array.prototype.slice.apply(arguments));
+
+        var that = this,
+            data = this.getData();
+
+        for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
+            var key,
+                item = data[i];
+
+            $.each(this.header.fields, function (j, field) {
+                var value = item[field],
+                    column = that.options.columns[getFieldIndex(that.options.columns, field)];
+
+                value = calculateObjectValue(that.header,
+                    that.header.formatters[j], [value, item, i], value);
+
+                if ((!column.checkbox) || (!column.radio)) {
+                    if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'select'
+                        && column.searchable) {
+
+                        var selectControl = $('.' + column.field),
+                            iOpt = 0,
+                            exitsOpt = false,
+                            options;
+                        if (selectControl !== undefined) {
+                            options = selectControl.get(0).options;
+
+                            if (options.length === 0) {
+
+                                //Added the default option
+                                selectControl.append($("<option></option>")
+                                    .attr("value", '')
+                                    .text(''));
+
+                                selectControl.append($("<option></option>")
+                                    .attr("value", value)
+                                    .text(value));
+                            } else {
+                                for (; iOpt < options.length; iOpt++) {
+                                    if (options[iOpt].value === value) {
+                                        exitsOpt = true;
+                                        break;
+                                    }
+                                }
+
+                                if (!exitsOpt) {
+                                    selectControl.append($("<option></option>")
+                                        .attr("value", value)
+                                        .text(value));
+                                }
+                            }
+                        }
+                    }
+                }
+            });
+        }
+    };
+
+    BootstrapTable.prototype.initSearch = function () {
+        _initSearch.apply(this, Array.prototype.slice.apply(arguments));
+
+        var that = this;
+        var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
+
+        //Check partial column filter
+        this.data = fp ? $.grep(this.data, function (item, i) {
+            for (var key in fp) {
+                var fval = fp[key].toLowerCase();
+                var value = item[key];
+                value = calculateObjectValue(that.header,
+                    that.header.formatters[$.inArray(key, that.header.fields)],
+                    [value, item, i], value);
+
+                if (!($.inArray(key, that.header.fields) !== -1 &&
+                    (typeof value === 'string' || typeof value === 'number') &&
+                    (value + '').toLowerCase().indexOf(fval) !== -1)) {
+                    return false;
+                }
+            }
+            return true;
+        }) : this.data;
+    };
+
+    BootstrapTable.prototype.onColumnSearch = function (event) {
+        var text = $.trim($(event.currentTarget).val());
+        var $field = $(event.currentTarget).parent().parent().parent().data('field')
+
+        if ($.isEmptyObject(this.filterColumnsPartial)) {
+            this.filterColumnsPartial = {};
+        }
+        if (text) {
+            this.filterColumnsPartial[$field] = text;
+        } else {
+            delete this.filterColumnsPartial[$field];
+        }
+
+        this.options.pageNumber = 1;
+        this.onSearch(event);
+        this.updatePagination();
+        this.trigger('column-search', $field, text);
+    };
+}(jQuery);