DataTable Sorting

DataTable allows you to sort data rows on the client side. There are 2 ways to invoke sorting in the table:

There is a chapter about sorting in Webix tutorials.

Sorting by a Click on the Header

When you click on the header, DataTable starts to display a special control indicating which column the table is currently sorted by and the direction of this sorting (ascending or descending). Each new click on the same header will reverse the sorting direction.

Columns can have different type of content (numbers, strings, dates) and each type of content requires its specific way of sorting.

Sorting Modes for Different Data Types

For this purpose, DataTable provides several sorting types to ensure correct sorting of columns:

  • "int" - compares numeric values;
  • "date" - compares dates;
  • "string" - compares string values;
  • "string_strict" - case-sensitive "string";
  • "text"- compares visible item text (including template), datatable only;
  • "string_locale" - compares string values based on the locale;
  • "string_locale_strict" - case-sensitive "string_locale";
  • "text_locale" - compares visible item text based on the locale (including template), datatable only;
  • "server" - issues a server side request for a sorted dataset;
  • "raw" - a basic sorter with simple comparison (a>b and vice versa);
  • a custom sorting type.

To enable sorting and assign the appropriate sorting type to a column, you should specify the sort attribute among the column parameters and set it to one of the types.

Sorting configuration

webix.ui({
    view:"datatable",
    columns:[
        { id:"title", header:"Film title",    sort:"string"},
        { id:"year",  header:"Release year", sort:"int"}
    ]
});

Related sample:  Sorting. Using Built-in Means

The above mentioned sorting modes work with column values defined by their ID attributes and ignore values either defined by column templates (except sort:"text") or provided by column options.

In the sample column below, column titles are sorted, yet categories are displayed (column template overrides column ID during rendering):

{ id:"title", template:"#cat_id#", header:"Category ID" }

In the sample column below, option IDs are sorted, yet option values are displayed:

{ id:"cat_id",  header:"Category", collection:[
    { id:1, value:"Crime"}, { id:2, value:"Thriller" }]
}

Sorting by visible text

Sorting by visible text is enabled with the help of the "text" sorting mode that switches on string comparison for the values actually displayed in datatable columns.

It takes into account column values defined by templates and collection values rather than IDs:

columns:[
    { id:"title",template:"#cat_id#", header:"Category ID", sort:"text" },
    { id:"cat_id",  header:"Category",sort:"text", collection:[
        { id:1, value:"Crime"}, { id:2, value:"Thriller" }]
    }
]

Related sample:  Sorting. Using Built-in Means

Sorting by dates

Sorting by dates is enabled by setting the "date" sorting mode.

webix.ui({
    view:"datatable",
    columns:[
        {
            header:"Y-m-d",
            sort:"date",
            id:"start",
            format:webix.Date.dateToStr("%Y-%m-%d")
        },
        {
            header:"m/d/Y",
            sort:"date",
            id:"start",
            format:webix.Date.dateToStr("%m/%d/%y")
        },
    ],
    data:[
        { text:"Joint 2", start:new Date(2011,1,14) },
        { text:"Finish", start:new Date(2012,11,12) }
    ]
});

Related sample:  Using Date Templates

Though dates are presented as strings, they are sorted as date objects. So if dates are stored as strings you need to convert them to DateTime objects before sorting. For this, you can either map string values:

// a column object
{
   "map":"(date)#createdDate#",  "id": "createdDate",
   "sort": "date",  "header": "Date Added", "editor": "date"
}

or provide the related parser to fill the datatable with the correct object dates:

view:"datatable",
scheme:{
    $init:function(obj){
        obj.createdDate = /*parse string into date*/
    }
}

Related sample:  Converting Strings to Dates

The detailed information on string-to-date conversion is given in Working with Dates.

Triggering Server-side Sorting on the Client Side

It's possible to issue a request to server to sort data in backend and reload the sorted dataset to the datatable:

The option is enabled by server sorting mode:

view:"datatable",
columns:[
    { id:"package", header:"Name", sort:"server"},
    {..}
],
url:"data.php"

Related sample:  Datatable: Serverside Filtering and Sorting

Now header clicking will trigger a server-side GET request with the following parameter: sort[package]=desc (data.php?sort[package]=desc), which allows sending:

  • operation name (sort);
  • data property to sort by (here: package);
  • sorting order (here: descending).

The new data will be loaded to the datatable and replace the initial dataset.

If serverFilter is enabled for this column, the data will be both filtered and sorted on the server side before returning to the client.

Multiple sorting

You can also sort several columns at once, by defining sorting mode "multi" via the sort property:

{
    view:"datatable", sort:"multi",
    autoConfig:true, url:"data/films"
}

You can also sort data by API:

$$("grid").sort([
    {
        by:"title", dir:"asc"
    },{
        by:"rank", dir:"asc"
    }
]);

To mark the sorted columns with the arrow (asc/desc) sign and the ordinal number in the header, use the markSorting method after sort().

To include several columns into sorting, user must click the needed header with Ctrl key pressed.

Related sample:  DataTable: Sorting By Multiple Columns

Custom Sorting Functions

If you want to apply custom sorting behavior, you can define the related logic in a function and set this function as the value of the sort attribute.

This function will be called for each pair of adjacent values and return 1,-1 or 0:

  • 1 - the second object goes before the first one;
  • -1 - the first object goes before the second one;
  • 0 - the order of both objects doesn't change.

The function can be defined in a general way:

Using custom functions for sorting DataTable

function sortByParam(a,b){
    a = a.rank;
    b = b.rank;
    return a > b ? 1 : (a < b ? -1 : 0);
};
 
webix.ui({
    view:"datatable",
    columns:[
        { id:"title",   header:"Film title", sort:sortByParam },
        // more columns
    ]
});

Related sample:  Sorting Datatable. Using Custom Sorting Functions

Programmatic Sorting

You should use the sort() method to invoke sorting on some event or action, i.e button click or page load.

Sorting DataTable on the button click

webix.ui({
    rows:[
        { view:"datatable", id:"grid", ... },
        { view:"button", value:"Sort table", click:function(){
            $$("grid").sort("#title#", "asc", "string");
        } }
    ]
});

Related sample:  Sorting Datatable. Using Sorting Methods

Controlling header sorting mark

You can show and hide the sorting sign (˄/˅) by calling the markSorting() method with the following parameters:

  • column_id - ID of the column you want to draw a sorting sign for;
  • direction - sorting direction;
  • preserve - instructs to preserve previous sorting marker.

When used with no arguments, the method removes all the sorting signs from the datatable headers.

Canceling sorting

grid = webix.ui({ view:"datatable", ...});
 
grid.markSorting("title", "asc");

Related sample:  Sorting Datatable. Using Sorting Methods

Adding Custom Sorting Type

You can define your own sorting type via the sorting.as property of the webix.DataStore.prototype object.

You need to specify a function that describes a new type of sorting as follows:

webix.DataStore.prototype.sorting.as.sort_type = function(a,b,prop){
    return a[prop] > b[prop] ? 1 : -1;
}

where a, b are cell values from the related column.

For example, let's set a new type "bylength" to sort data by the text length:

webix.DataStore.prototype.sorting.as.bylength = function(a,b,prop){
    return a[prop].length > b[prop].length ? 1 : -1;
}

To apply a custom sorting type to a column, you need to set its name as the value of the sort property for the corresponding column:

{
    view:"datatable",
    columns:[
        { id:"product1", sort:"bylength" },
        { id:"product2", sort:"bylength" },
        { id:"product3", sort:"bylength" }
    ]
}

You can also set the newly created sorting type as a value of the as parameter of the "sort()" method:

$$("datatable1").sort({
   by:"name",
   dir:"desc",
   as:"bylength"
});
Back to top
If you have not checked yet, be sure to visit site of our main product Webix mvc library and page of javascript datagrid product.