Programmatically setting grid sort

Matteo Piazza picture Matteo Piazza · Dec 13, 2012 · Viewed 45.3k times · Source

Is it possible to programmatically set the sort parameter of a KendoUI DataSource before reading data and avoiding a second server reading? The scope is setting a default sort on a certain user interaction. How?

Here is an example of what I am trying to do, because the answers are not getting to the point (or maybe I am not understanding how things work).

I define a Kendo DataSource with an initial sort:

var datasource = new kendo.data.DataSource({
    parameterMap: function (inputParams, operation) {
        return JSON.stringify(inputParams)
    },
    // default sort
    sort: [
        {field: "field_1", dir: "asc"},
        {field: "field_2", dir: "asc"}
    ]
});

This DataSource is bound to a Kendo grid:

var grid = $("element").kendoGrid({
    dataSource: datasource   
});

Then I have a button that calls a "read" on the DataSource and populates the grid with the first page of data:

$("#btn").bind("click", function(e) {
    datasource.page(1);
}); 

This way, after clicking the button, the user gets data ordered by "field_1" and "field_2", and the grid shows this sort on column headers. The user then could reorder the data in any way, by clicking on column header.

What I would like to do is to reset the default sort to the initial one, as defined in the DataSource declaration, showing it again on column headers, and without create a new DataSource again.

Something like:

$("#btn").bind("click", function(e) {
    datasource.sort = [
        {field: "field_1", dir: "asc"},
        {field: "field_2", dir: "asc"}
    ]; 
    datasource.page(1);
}); 

The solutions provided do not seem to reach the point (and still I do not understand why I am losing reputation points for a legitimate question that seems to be not so trivial and should be addressed by the framework).

Please show me I am wrong (I am not worrying about losing reputation - I would like to just understand how to solve a problem).

Answer

Nanetxe picture Nanetxe · Jul 12, 2013
var kendoGrid = $("#grid").data('kendoGrid');
var dsSort = [];
dsSort.push({ field: "fieldName1", dir: "asc" });
dsSort.push({ field: "fieldName2", dir: "desc" });
kendoGrid.dataSource.sort(dsSort);