Search code examples
jqueryvalidationsortinghandsontable

Handsontable conflict between validating and sorting


In my Handsontable, I would like to allow users to be able to sort by the rows that have failed validation. I have added a blank column at the beginning of the data set, and in the aftervalidate hook, I set this field to 1 for rows that fail.

afterValidate: function (isValid, value, row, prop, source) {
    if (!isValid) hot.setDataAtCell(hot.sortIndex[row][0], 0, "1");
    else if (source=="edit") hot.setDataAtCell(hot.sortIndex[row][0], 0, "");
},
columnSorting: true,
afterColumnSort: function (column, order) {
    hot.validateCells(function (valid) {});
}

I am running into a weird issue where it is not always flagging the correct row. As you can see in this fiddle, if you sort a column repeatedly, on every third sort the error flag does not match up with the invalid row and in the console there is an "Uncaught TypeError: Cannot read property '0' of undefined".

https://jsfiddle.net/dk9d1aqr/3/

Also, validation totally fails if you try to set the table to start sorted:

//validation works with this
columnSorting: true,
//validation fails with this
columnSorting: {column: 2, sortOrder: true},

Any ideas on how to get validation and sorting working together?


Solution

  • My issue was that I misread the sortIndex method. It is supposed to be passed the sorted row number and returns the physical row number from the underlying dataset (backwards from how I was trying to use it).

    I had to implement the untranslateRow function to return the value I needed. http://jsfiddle.net/dk9d1aqr/4/

    It appears that when you are clicking the headers to sort that it rotates between ascending, descending, and unsorted (error thrown here). I added a return row; alternate path which solved the Uncaught TypeError.