0

Hi I'm trying to write a grid filter in Vaadin framework. My aim is that a user has a combo box with dropdown list and can choose that he wants to see only entries from 3, 6, 9 weeks ago. I wrote it but I have a problem becasue it doesnt work as default filter. I mean if I open a page the grid is displayed without filter. I need first click on the button. Is it possible to filter grid by default, showing only 3 weeks entries? How can I manage it?

     final ComboBox<Integer> timePeriodSelector = new ComboBox<>("Time Filter", Arrays.asList(3, 6, 9);
    timePeriodSelector.setEmptySelectionAllowed(false);
    timePeriodSelector.setTextInputAllowed(false);
    timePeriodSelector.setValue(3);
    timePeriodSelector.addValueChangeListener(this::onWeekChange);

...

private void onWeekChange(HasValue.ValueChangeEvent<Integer> event) {

    switch (event.getValue()) {
    case 3:
        dateToCompare = LocalDate.now().minusDays(21);
        break;
    case 6:
        dateToCompare = LocalDate.now().minusDays(42);
        break;
    case 9:
        dateToCompare = LocalDate.now().minusDays(63);
        break;
    default:
        dateToCompare = LocalDate.now().plusDays(21);
    }

    ListDataProvider<CcEvent> dataProvider = (ListDataProvider<CcEvent>) eventsOverview.getDataProvider();
    dataProvider.setFilter(CcEvent::getReportingDate,
            date -> compareDates(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), dateToCompare));
}

private Boolean compareDates(LocalDate dateFromTable, LocalDate dateFromFilter) {
    return dateFromTable.isBefore(dateFromFilter);
}
Anna K
  • 1,666
  • 4
  • 23
  • 47
  • Change order of your calls. You should call first `addValueChangeListener` and right after that `setValue`. It should run the listener code and filter you container. – Shirkam Sep 13 '17 at 09:04

1 Answers1

0

that piece of code looks nice and is how the Grid filter is intented. However all you have to do is switch your setValue call with your addValueChangeListener call.

Setting the listener before setting the value ensures that the ValueChangedEvent is triggered!

  • Do you mean I need to change the order of methods like here? timePeriodSelector.addValueChangeListener(this::onWeekChange); timePeriodSelector.setValue(3); It doesnt work :( – Anna K Sep 07 '17 at 13:32
  • Yeah thats what I thought was all you needed to do. I tried your code with an `addValueChangeListener( x -> Notification.show(x.toString())` and if setValue is called before the addValueChangeListener the Notification is not shown. However if it is called afterwards the Notification is shown. – Manuel Kollegger Sep 07 '17 at 14:09
  • Another idea: Is the Dataprovider for `eventsOverview` set by calling `setItems`or something similar? If by the time `setValue`is called the Dataprovider is not yet set there is no data for filtering available yet – Manuel Kollegger Sep 07 '17 at 14:17