Alexander Ley:
This is a nice documentation, but as far as I have read it, it only describes what can be done but no word about the Renderer vs. ValueProvider difference.
The TemplateRenderer seems to support automatic sorting (with more than one ValueProvider):
For in-memory sorting to work correctly, the values returned by the ValueProviders in the TemplateRenderer (Person::getName and Person::getEmail in this example) should implement Comparable.
This part requires the context from above:
Example: Using the addColumn method with TemplateRenderer to set column sort properties.
grid.addColumn(TemplateRenderer.<Person> of(
"<div>[[item.name]
]<br>" +
"<small>[[item.email]
]</small></div>")
.withProperty("name", Person::getName)
.withProperty("email", Person::getEmail),
"name", "email") // <---
.setHeader("Person")
* For in-memory sorting to work correctly, the values returned by the ValueProviders in the TemplateRenderer (Person::getName and Person::getEmail in this example) should implement Comparable.
Here the sort properties are on the second to last row (the one with the two Strings, "name", "email")
- the data is sorted first by name
and then by email
. Thus the Grid also needs to be created with the bean scanning new Grid(Person.class)
constructor for the example to work.
You do kind of need to read between the lines to find out that Renderer columns are not automatically sortable; the main idea is stated here, though:
By default, all property-based columns are sortable, if the property type implements Comparable.
Many data types, such as String, Number, primitive types and Date/LocalDate/LocalDateTime are Comparable, and therefore also sortable, by default.
To make the column of a non-comparable property type sortable, you need to define a custom Comparator. See Column Sorting for more.
And about “Using a Comparator”:
If you need custom logic to compare items for sorting, or if your underlying data is not Comparable, you can set a Comparator for your column.
I think it should be documented in the API (e.g. Grid.Column.setSortable()) in which cases a user defined Comparator is needed. It seems not to be straight forward.
Not sure if setSortable
’s JavaDoc is the right place, as columns are sortable by default with an in-memory dataprovider - there’s no need to call setSortable
unless you’re calling it to disable sorting (which is the opposite of what the problem is) or maybe to re-enable sorting later after it has been disabled.
I would assume that a typical scenario for needing help is that you have tried a bunch of regular ValueProvider or property-based automatic columns first and you have seen that the sorting works there (without calling setSortable
). Then when you’re adding something more complex with a Renderer
, it suddenly creates a column that is no longer sortable, so maybe it would make most sense to have something mentioned in the JavaDoc of addColumn(Renderer)
. What do you think?