Browse Source

Added the toolbar extension

Dennis Hernández 10 years ago
parent
commit
c0dd56b020
2 changed files with 155 additions and 62 deletions
  1. 41 0
      src/extensions/toolbar/README.md
  2. 114 62
      src/extensions/toolbar/bootstrap-table-toolbar.js

+ 41 - 0
src/extensions/toolbar/README.md

@@ -0,0 +1,41 @@
+# Table Toolbar
+
+Use Plugin: [bootstrap-table-toolbar](https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/toolbar)
+
+## Usage
+
+```html
+<script src="extensions/toolbar/bootstrap-table-toolbar.js"></script>
+```
+
+## Options
+
+### advancedSearch
+
+* type: Boolean
+* description: Set true to allow the advanced search.
+* default: `false`
+
+### idForm
+
+* type: String
+* description: Must be set to know the idform.
+* default: `advancedSearch`
+
+### actionForm
+
+* type: String
+* description: Set the action of the form (pop-up).
+* default: ``
+
+### idTable
+
+* type: String
+* description: Set the id of the table to create the pop-up form.
+* default: ``
+
+## Events
+
+### onColumnAdvancedSearch(column-advanced-search.bs.table)
+
+* Fired when we are searching into the advanced search form

+ 114 - 62
src/extensions/toolbar/bootstrap-table-toolbar.js

@@ -1,6 +1,6 @@
 /**
  * @author: aperez <aperez@datadec.es>
- * @version: v1.0.0
+ * @version: v2.0.0
  *
  * @update Dennis Hernández <http://djhvscf.github.io/Blog>
  */
@@ -28,15 +28,37 @@
         return flag ? str : '';
     };
 
+    var calculateObjectValue = function (self, name, args, defaultValue) {
+        if (typeof name === 'string') {
+            // support obj.func1.func2
+            var names = name.split('.');
 
-    var showAvdSearch = function(pColumns, pObjSearch, searchText) {
+            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;
+    };
+
+    var showAvdSearch = function(pColumns, searchTitle, searchText, that) {
         if (!$("#avdSearchModal").hasClass("modal")) {
             var vModal = "<div id=\"avdSearchModal\" class=\"modal fade\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\" aria-hidden=\"true\">";
             vModal += "<div class=\"modal-dialog modal-xs\">";
             vModal += " <div class=\"modal-content\">";
             vModal += "  <div class=\"modal-header\">";
             vModal += "   <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\" >&times;</button>";
-            vModal += "   <h4 class=\"modal-title\">Buscador Avanzado</h4>";
+            vModal += sprintf("   <h4 class=\"modal-title\">%s</h4>", searchTitle);
             vModal += "  </div>";
             vModal += "  <div class=\"modal-body modal-body-custom\">";
             vModal += "   <div class=\"container-fluid\" id=\"avdSearchModalContent\" style=\"padding-right: 0px;padding-left: 0px;\" >";
@@ -47,26 +69,21 @@
             vModal += "</div>";
 
             $("body").append($(vModal));
-            var vFormAvd = createFormAvd(pColumns, pObjSearch, searchText);
-            $('#avdSearchModalContent').append(vFormAvd.join(''));
 
-            $("#btnSearchAvd").click(function() {
-                var vFormData = $("#" + pObjSearch.idForm).serializeJSON();
-                var vText = $('#' + pObjSearch.idTable).parents('.bootstrap-table').find('.search input').val();
-
-                $.extend(vFormData, {
-                    searchText: vText
-                });
-                var sFunctionData = JSON.stringify(vFormData);
-                BootstrapTable.DEFAULTS.searchText = sFunctionData;
+            var vFormAvd = createFormAvd(pColumns, searchText, that),
+                timeoutId = 0;;
 
-                //TODO: Implement the search logic
-                //BootstrapTable.prototype.onSearch(this,$.Event('keyup'));
-                /*********************
+            $('#avdSearchModalContent').append(vFormAvd.join(''));
 
-                  * Here, I want to call the method onSearch.
+            $('#' + that.options.idForm).off('keyup blur', 'input').on('keyup blur', 'input', function (event) {
+                clearTimeout(timeoutId);
+                timeoutId = setTimeout(function () {
+                    that.onColumnAdvancedSearch(event);
+                }, that.options.searchTimeOut);
+            });
 
-                ***********************/
+            $("#btnCloseAvd").click(function() {
+                $("#avdSearchModal").modal('hide');
             });
 
             $("#avdSearchModal").modal();
@@ -75,16 +92,16 @@
         }
     };
 
-    var createFormAvd = function(pColumns, pObjSearch, searchText) {
+    var createFormAvd = function(pColumns, searchText, that) {
         var htmlForm = [];
-        htmlForm.push(sprintf('<form class="form-horizontal" id="%s" action="%s" >', pObjSearch.idForm, pObjSearch.actionForm));
+        htmlForm.push(sprintf('<form class="form-horizontal" id="%s" action="%s" >', that.options.idForm, that.options.actionForm));
         for (var i in pColumns) {
             var vObjCol = pColumns[i];
             if (!vObjCol.checkbox && vObjCol.visible && vObjCol.searchable) {
                 htmlForm.push('<div class="form-group">');
                 htmlForm.push(sprintf('<label class="col-sm-4 control-label">%s</label>', vObjCol.title));
                 htmlForm.push('<div class="col-sm-6">');
-                htmlForm.push(sprintf('<input type="text" class="form-control input-md" name="%s" placeholder="%s">', vObjCol.title, vObjCol.title));
+                htmlForm.push(sprintf('<input type="text" class="form-control input-md" name="%s" placeholder="%s" id="%s">', vObjCol.field, vObjCol.title, vObjCol.field));
                 htmlForm.push('</div>');
                 htmlForm.push('</div>');
             }
@@ -92,7 +109,7 @@
 
         htmlForm.push('<div class="form-group">');
         htmlForm.push('<div class="col-sm-offset-9 col-sm-3">');
-        htmlForm.push(sprintf('<button type="button" id="btnSearchAvd" class="btn btn-default" >%s</button>', searchText));
+        htmlForm.push(sprintf('<button type="button" id="btnCloseAvd" class="btn btn-default" >%s</button>', searchText));
         htmlForm.push('</div>');
         htmlForm.push('</div>');
         htmlForm.push('</form>');
@@ -101,12 +118,21 @@
     };
 
     $.extend($.fn.bootstrapTable.defaults, {
-        advancedSearch: undefined,
-        idTable: undefined
+        advancedSearch: false,
+        idForm: 'advancedSearch',
+        actionForm: '',
+        idTable: undefined,
+        onColumnAdvancedSearch: function (field, text) {
+            return false;
+        }
     });
 
     $.extend($.fn.bootstrapTable.defaults.icons, {
-        advancedSearch: 'glyphicon-chevron-down'
+        advancedSearchIcon: 'glyphicon-chevron-down'
+    });
+
+    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
+        'column-advanced-search.bs.table': 'onColumnAdvancedSearch'
     });
 
     $.extend($.fn.bootstrapTable.locales, {
@@ -114,7 +140,7 @@
             return 'Advanced search';
         },
         formatAdvancedSearchButton: function() {
-            return "Search";
+            return "Close";
         }
     });
 
@@ -122,57 +148,40 @@
 
     var BootstrapTable = $.fn.bootstrapTable.Constructor,
         _initToolbar = BootstrapTable.prototype.initToolbar,        
-        _load = BootstrapTable.prototype.load;
+        _load = BootstrapTable.prototype.load,
+        _initSearch = BootstrapTable.prototype.initSearch;
 
     BootstrapTable.prototype.initToolbar = function() {
         _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
 
-        var that = this,
-            htmlBtns = [],
-            $search,
-            advSearch = {
-                active: false,
-                idTable: '',
-                idForm: '',
-                actionForm: ''
-            };
-
-        if (typeof this.options.advancedSearch !== 'undefined') {
-            advSearch = this.options.advancedSearch;
+        if (!this.options.search) {
+            return;
         }
 
-        if (advSearch.active) {
-            htmlBtns.push(sprintf('<div class="btn-group" role="group"><button class="btn btn-default' + (that.options.iconSize === undefined ? '' : ' btn-' + that.options.iconSize) + '" type="button" name="advancedSearch" title="%s">',
-                    that.options.formatAdvancedSearch()),
-                sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.advancedSearch),
-                '</button></div>');
+        if (!this.options.advancedSearch) {
+            return;
+        }
 
-            // TODO: For now need the showColumns set to true. CHANGE this!
-            that.$toolbar.find('.columns').prepend(htmlBtns.join(''));
+        var that = this,
+            html = [];
 
-            that.$toolbar.find('button[name="advancedSearch"]')
-                .off('click').on('click', function() {
-                    showAvdSearch(that.options.columns, advSearch, that.options.formatAdvancedSearchButton());
-                });
-        }
+        html.push(sprintf('<div class="columns columns-%s btn-group pull-%s" role="group">', this.options.buttonsAlign, this.options.buttonsAlign));
+        html.push(sprintf('<button class="btn btn-default%s' + '" type="button" name="advancedSearch" title="%s">', that.options.iconSize === undefined ? '' : ' btn-' + that.options.iconSize, that.options.formatAdvancedSearch()));
+        html.push(sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.advancedSearchIcon))
+        html.push('</button></div>');
 
-        if (that.options.searchTimeOut === -1) {
-            $search = that.$toolbar.find('.search input');
-            $search.off('keyup').on('keyup', function(event) {
-                var text = $.trim($(event.currentTarget).val());
-                //TODO: Check this logic
-                if (event.which === 13) {
-                    that.onSearch(event);
-                }
+        that.$toolbar.prepend(html.join(''));
+
+        that.$toolbar.find('button[name="advancedSearch"]')
+            .off('click').on('click', function() {
+                showAvdSearch(that.options.columns, that.options.formatAdvancedSearch(), that.options.formatAdvancedSearchButton(), that);
             });
-        }
     };
 
     BootstrapTable.prototype.load = function(data) {
         _load.apply(this, Array.prototype.slice.apply(arguments));
 
         if (typeof this.options.idTable === 'undefined') {
-            //TODO: Should we show a error message?
             return;
         } else {
             if (!firstLoad) {
@@ -183,4 +192,47 @@
             }
         }
     };
+
+    BootstrapTable.prototype.initSearch = function () {
+        _initSearch.apply(this, Array.prototype.slice.apply(arguments));
+
+        var that = this;
+        var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
+
+        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.onColumnAdvancedSearch = function (event) {
+        var text = $.trim($(event.currentTarget).val());
+        var $field = $(event.currentTarget)[0].id;
+
+        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-advanced-search', $field, text);
+    };
 }(jQuery);