AlliterativeAlice
AlliterativeAlice

Reputation: 12577

Custom Sort on Kendo Grid that can be Triggered Programmatically

I have a kendo grid and want certain rows to stay pinned at the top of the grid after sorting. I can achieve this by specifying a custom sort on every column. For example:

<script>
    var ds = new kendo.data.DataSource({
        data: [
            { name: "Jane Doe", age: 30, height: 170, pinToTop: false },
            { name: "John Doe", age: 33, height: 180, pinToTop: false },
            { name: "Sam Doe", age: 28, height: 185, pinToTop: true },
            { name: "Alex Doe", age: 24, height: 170, pinToTop: false },
            { name: "Amanda Doe", age: 25, height: 165, pinToTop: true }
        ]
    });

    $('#grid').kendoGrid({
        dataSource: ds,
        sortable: {mode: 'single', allowUnsort: false},
        columns: [{
            field: "name",
            title: "Name",
            sortable: {
                compare: function (a, b, desc) {
                    if (a.pinToTop && !b.pinToTop) return (desc ? 1 : -1);
                    if (b.pinToTop && !a.pinToTop) return (desc ? -1 : 1);
                    if (a.name > b.name) return 1;
                    else return -1;
                }
            }
        }
        //Other columns would go here
        ]
    });
</script>

This works fine when the grid is sorted by the user clicking on a column header. However, if I want to sort the grid using Javascript code, like so:

$('#grid').data('kendoGrid').dataSource.sort({field: 'age', dir: 'asc'});

The pinToTop field is ignored. This is because the sort is performed on the DataSource, but the custom sort logic is part of the grid.

JSFiddle Example

I need to either:

Or:

Upvotes: 2

Views: 7137

Answers (2)

Lee
Lee

Reputation: 21

This is an old question, but here is an answer for those coming across this question, like I did.

Define the comparison as a function and pass it to the DataSource:

var compareName = function (a, b, desc) {
            if (a.pinToTop && !b.pinToTop) return (desc ? 1 : -1);
            if (b.pinToTop && !a.pinToTop) return (desc ? -1 : 1);
            if (a.name > b.name) return 1;
            else return -1;
        }

$('#grid').data('kendoGrid').dataSource.sort({field: 'age', dir: 'asc', compare: compareName);

Works in version 2017.2.621

Upvotes: 2

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

It wasn't quite what I wanted, but I was able to solve this issue by sorting on multiple fields and including the pinToTop field first:

$('#grid').data('kendoGrid').dataSource.sort([{field: 'pinToTop', dir: 'desc'},{field: 'age', dir: 'asc'}]);

Upvotes: 2

Related Questions