How to set the default sorting in a grid? Vaadin 23

https://vaadin.com/docs/latest/components/grid/flow
While manual sorting works fine, how can I set the default sorting?

You can call

sort(List<GridSortOrder<T>> order)

Alternatively, you can sort the dataprovider

How?

       private BackEndDataProvider<SafeguardDTO, Void> getSafeguards(Filter filter) {
            CallbackDataProvider<SafeguardDTO, Void> dataProvider = DataProvider.fromFilteringCallbacks(query -> pool.getSafeguardPage(filter.getName(), filter.getTyp(), filter.getFactor(), Paging.toPageable(query)).stream(), query -> (int) pool.getSafeguardCount(filter.getName(), filter.getTyp(), filter.getFactor()));
            dataProvider.setSortOrder(new QuerySortOrder("name", SortDirection.DESCENDING));
            return dataProvider;
        }

or like this:

grid.sort(List.of(new GridSortOrder<>(nameColumn, SortDirection.ASCENDING)));

Thanks!

Depends on the DataProvider. In-memory dataproviders have setSortComparator and addSortComparator for the “default” sorting, and you can use setSortOrder/addSortOrder to change it dynamically. With a lazy-loading DataProvider, there’s also setSortOrder with sort properties and direction, but you’ll need to implement the “default” sorting in the backend (or provide an API for that)

The upside of sorting the DataProvider instead of the Grid is that you can reuse the DataProvider, and you’ll maintain the sorting. This is sometimes very useful.

Thanks. I never had the requirement to reuse a DataProvider (90% of the time I use a lazy data provider) as it’s always bound to the specific grid. So I use grid.sort because it feels more “natural”