Calling sort on slickgrid

Siddharth picture Siddharth · Mar 13, 2012 · Viewed 22.7k times · Source

In the slickgrid I'm able to set the sort column and it's sort direction using the grid.SetSortColumn(colName,true/false). This only sets the sorting glyph but does no sorting. Is there a way to call the sort event handler. I've defined the sort handler like grid.onSort.subscribe(function(){});

Answer

Mr.Hunt picture Mr.Hunt · Apr 25, 2012

The behavior you are observing is correct.

    grid.setSortColumn(columnId, isAsc);

only updates the glyph on the sort column. In your case, you will initially need to sort the data, and then use setSortColumn to update the glyph on sortColumn. You can reuse sorter used in onSort event like this:

   var gridSorter = function(columnField, isAsc, grid, gridData) {
       var sign = isAsc ? 1 : -1;
       var field = columnField
       gridData.sort(function (dataRow1, dataRow2) {
              var value1 = dataRow1[field], value2 = dataRow2[field];
              var result = (value1 == value2) ?  0 :
                         ((value1 > value2 ? 1 : -1)) * sign;
              return result;
       });
       grid.invalidate();
       grid.render();
   }
   var grid = new Slick.Grid($gridContainer, gridData, gridColumns, gridOptions);

   //These 2 lines will sort you data & update glyph while loading grid     
   //columnField is field of column you want to sort initially, isAsc - true/false
   gridSorter(columnField, isAsc, grid, gridData);

   //I had the columnField, columnId same else used columnId below
   grid.setSortColumn(columnField, isAsc); 

   grid.onSort.subscribe(function(e, args) {
        gridSorter(args.sortCol.field, args.sortAsc, grid, gridData);
   });

How I arrived on this solution?

Read comments here. https://github.com/mleibman/SlickGrid/issues/325