Wednesday, November 4, 2015

jqGrid Date Picker for column filtering

Using jqGrid 4.9.2, you can add a date picker to a column filter using the following code:

 grid.setFilterDate = function(table, column) {  
     $('#' + table).jqGrid('setColProp', column, {  
       searchoptions: {  
         dataInit: _loadDatePicker  
       },  
       dataEvents: [{  
         type: 'change',  
         fn: function (e) {  
           console.log("change via datePicker failed - search dialog detected");  
           //table.toggleToolbar();  
         }  
       }]  
     });      
   }  

 function _loadDatePicker (filters) {  
     setTimeout(function() {  
       $(filters).datepicker({  
         dateFormat: 'mm/dd/yy',  
         autoSize: true,  
         changeYear: true,  
         changeMonth: true,  
         showButtonPanel: true,  
         showWeek: true,  
         onSelect: function() {  
           var $grid, grid;  
           if (typeof (this.id) === "string" && this.id.substr(0, 3) === "gs_") {  
             // in case of searching toolbar  
             $grid = $(this).closest('div.ui-jqgrid-hdiv')  
               .next('div.ui-jqgrid-bdiv')  
               .find("table.ui-jqgrid-btable:first");  
             if ($grid.length > 0) {  
               grid = $grid[0];  
               if ($.isFunction(grid.triggerToolbar)) {  
                 setTimeout(function() {  
                   grid.triggerToolbar();  
                 }, 50);  
               }  
             }  
           } else {  
             // refresh the filter in case of  
             // searching dialog   
             $(this).trigger('change');  
           }  
         }  
       });  
     }, 100);  
   };  

To filter when a date is selected, use the onSelect option:

      onSelect: function() {   
       var $grid, grid;   
       if (typeof (this.id) === "string" && this.id.substr(0, 3) === "gs_") {   
        // in case of searching toolbar   
        $grid = $(this).closest('div.ui-jqgrid-hdiv')   
         .next('div.ui-jqgrid-bdiv')   
         .find("table.ui-jqgrid-btable:first");   
        if ($grid.length > 0) {   
         grid = $grid[0];   
         if ($.isFunction(grid.triggerToolbar)) {   
          setTimeout(function() {   
           grid.triggerToolbar();   
          }, 50);   
         }   
        }   
       } else {   
        // refresh the filter in case of   
        // searching dialog    
        $(this).trigger('change');   
       }   
      }   

The key to filtering onSelect is grid.TriggerToolbar(). Because setFilterDate is refactored, you either need to pass in the grid "table" ID or search for it inside the function.

Source

No comments: