Search code examples
vaadinvaadin8vaadin-grid

How to re-apply filters in Vaadin 8 Grid


I've added filters to my Grid such as the following:

filterTextField.addValueChangeListener(event -> {
        myListDataProvider.addFilter(
                columnName, 
                value-> value.toLowerCase().contain(filterTextField.getValue()));
    });

This sets and applies the filter. However later I perform an action on the grid which necessitates a reload of the items such that:

grid.setItems(reloadItemsDueToAction());

When I do this the filterTextField is of course still populate and the grid is reloaded, however the problem is that I don't know how to re-apply the filters that were set in the ListDataProvider so that the grid is once again filtered according to the filterTextField. The filters should still be set in the ListDataProvider but how do I apply them in the grid?


Solution

  • It seems to me that currently (8.1.5) it is possible only by setting the DataProvider and filters again, for example:

    private ListDataProvider<Entity> ldp
       = new ListDataProvider<>(getGridItems()); // initial grid data
    
    // then somewhere update grid & re-apply filters
    
    SerializablePredicate<Entity> filter = ldp.getFilter(); // store filter
    ldp = new ListDataProvider<>( getGridItems() ); // new ldp with fresh data
    grid.setDataProvider(ldp); // instead of setItems()
    if(filter!=null) ldp.addFilter(filter); // re-apply stored filter
    

    The same fashion applied earlier also with Table/Container.

    If you use setItems() i guess Grid is not anymore using the previous DataProvider and setting filters to previous DataProvider will not propagate to Grid. I do not know if it is wise but if you really need to use setItems() then maybe something like this:

    ListDataProvider<Entity> ldp = ((ListDataProvider<Entity>)g.getDataProvider());
    SerializablePredicate<Entity> filter = ldp.getFilter();
    grid.setItems(getGridItems());
    ldp = ((ListDataProvider<Entity>)g.getDataProvider());
    if(filter!=null) ldp.addFilter(filter);
    

    Tested both with multiple filters.