Search code examples
sapui5

Sort table column with custom comparator


I have a table column which displays customers full names (first name + last name). However, I want to sort this column first by first name and then by last name. Therefore I added some comparator function in my controller:

_customNameComparator: function(value1, value2) {
    // Separate all words of the full name
    var aWordsName1 = value1.split(" ");
    var aWordsName2 = value2.split(" ");

    // Get the last and first names of the two names
    var sFirstName1 = value1.substring(0, value1.lastIndexOf(" "));
    var sLastName1 = aWordsName1[aWordsName1.length - 1];
    var sFirstName2 = value2.substring(0, value1.lastIndexOf(" "));
    var sLastName2 = aWordsName2[aWordsName2.length - 1];

    // 0 values are equal
    // -1 value1 smaller than value2
    // 1 value1 larger than value2

    if (sLastName1 === sLastName2) {
        if (sFirstName1 === sFirstName2) {
            return 0;
        } else if (sFirstName1 > sFirstName2) {
            return 1;
        } else {
            return -1;
        }
    } else if (sLastName1 > sLastName2) {
        return 1;
    } else {
        return -1;
    }
}

When the column Header is clicked, I try to call

var aSorter = [];
aSorter.push(new sap.ui.model.Sorter("FullName", bDescending, false, this._customNameComparator)); 
var oBinding = this.byId("tableTargetGroupDetails").getBinding("items");
oBinding.sort(aSorter);

The comparator does not work like this. The sorting is just as usual (by the full name). What do I do wrong?

And btw: I know that this can lead to some wrong sorting (e.g. for last names containing out of two or more words), but since it's "only" the sorting this is fine for me at the moment.


Solution

  • Unless your binding's operationMode is Client, your comparator will probably not work. You can set the mode where you do your binding using { parameters: { operationMode: 'Client' } }.