Search code examples
vaadin8

Vaadin 8 Grid select first row


Is there a simple way to select the first row shown in a Grid? I have of list of items and use the DataProvider.ofCollection(items) data provider. Simply selecting the first item of my backing list is not sufficient because I sort the Grid by one column which could make a different order than in the original list. Any idea?

I could use DataProvider.fetch method but it feels too complicated. Is there no built-in way?


Solution

  • What you can do is get the current sort Column Id and SortDirection, then with your data, sort and find the next object to select.

    For me, I had the same issue with TreeGrid (extends Grid) so this will be similar, minus the TreeData/RootItems part. Also, I only had sorting on "name".

    <!-- language: lang-java -->    
    List<GridSortOrder<MyPojo>> order = grid.getSortOrder();
    Column<MyPojo, ?> col = order.get(0).getSorted();
    SortDirection dir = order.get(0).getDirection();
    String colId = col.getId();
    
    if(colId.equals("name")) {
        Optional<MyPojo> first;
        if(dir.equals(SortDirection.ASCENDING)) {
            first = grid.getTreeData().getRootItems().stream()
                                        .sorted(Comparator.comparing(MyPojo::getName)).findFirst();
        }else {
            first = grid.getTreeData().getRootItems().stream()
                                    .sorted(Comparator.comparing(MyPojo::getName).reversed()).findFirst();
        }
        if(first.isPresent())
            grid.select(first.get());
    }