'Vaadin 14 Grid Sort on Non Class Atrtribute

I am trying to sort a Vaadin Grid with a back end data source.

However, I want to sort on the outcome of a comparator method, not on a property of the back end data source. This is how the column is added to the table:

grid.addColumn(p -> p.getNumberOfChoices()).setHeader("Choices").setComparator((c1, c2) -> c1.getNumberOfChoices().compareTo(c2.getNumberOfChoices())).setSortable(true);

It appears that I must apply the setSortProperty() method to have the grid sort to attempt a sort, but since I do not have a class property for this sort, this results in an exception.



Solution 1:[1]

It is only possible to sort based on a comparator if all items are loaded into memory. This does defeat the purpose of using a lazy loading data provider. This means that you have two options:

  1. Load all items into e.g a List and set them using Grid::setItems instead of using a lazy loading data provider.
  2. Implement your data provider to have explicit support for whatever string you pass to setSortProperty(). The provider implementation can access the property string through Query::getSortOrders. In cases like this, you probably need to implement it to explicit check for that case to make it do a custom SQL query or similar to lazy load items in the desired way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leif Åstrand