Search code examples
vaadinvaadin-gridvaadin14

How to disable unsorted state of vaadin 14


I use classic Vaadin Grid. However, I want to disable the 3rd option below. The Grid needs to show only descending order or ascending order. How to disable unsorted state?

By default, this is how column sorting in the Grid works:

  1. The first click on the column header sorts the column.

  2. The second click reverses the sort order.

  3. The third click resets the column to its unsorted state.

Here is my grid:

    private Grid<Read> grid2 = new Grid<>(Read.class);
    grid2.setColumns("type", "date", "message");

Thanks for your help.


Solution

  • The first somewhat clunky server-side workaround that comes to mind would be listening to the sort order change and re-sorting whenever a column disappears from the list. E.g.

    private final Set<String> currentlySortedColumns = new HashSet<String>();
    
    grid.setMultiSort(true);
    grid.addSortListener(e -> {
        List<GridSortOrder<SamplePerson>> sortOrderList = e.getSortOrder();
        List<String> notFound = new ArrayList<String>(
                currentlySortedColumns);
        for (GridSortOrder<SamplePerson> sortOrder : sortOrderList) {
            String key = sortOrder.getSorted().getKey();
            currentlySortedColumns.add(key);
            notFound.remove(key);
        }
        if (!notFound.isEmpty()) {
            for (String key : notFound) {
                sortOrderList.add(0, new GridSortOrder<>(
                        grid.getColumnByKey(key), SortDirection.ASCENDING));
            }
            grid.sort(sortOrderList);
        }
    });
    

    Note that since it only triggers re-sort after a server roundtrip, the non-sorted icon is visible for a moment before changing to point up again.