Search code examples
javavaadinvaadin7jpacontainer

JPA container OR filter - Vaadin application


I have a vaadin7 applicaiton and a JPA Container for an Entity class. I have ListSelect control that I use to filter that container

private ListSelect generateBrokerSelects() {
        ListSelect broker_ListSelect = new ListSelect("Broker:");
        JPAContainer<ReservationsBroker> containerBroker = JPAContainerFactory.makeReadOnly(ReservationsBroker.class, em);

        containerBroker.sort(new Object[]{"name"}, new boolean[]{true});

        broker_ListSelect.setContainerDataSource(containerBroker);
        broker_ListSelect.setMultiSelect(true);
        broker_ListSelect.setRows(4);
        broker_ListSelect.setItemCaptionPropertyId("name");

        return broker_ListSelect;
    }

I want to filter the JPA container based on the values selected on this ListSelect control.

public List<Container.Filter> getFilters() {
        List<Container.Filter> filters = new LinkedList<>();
        Container.Filter filter;

        Set brokerList = (Set) broker_ListSelect.getValue();
        if (brokerList.size() > 0) {
            for (Object brokerId : brokerList) {
                filter = new Compare.Equal("brokerId.id", brokerId);
                filters.add(filter);
            }

        return filters;
}
private void applyFilters() {
        container.removeAllContainerFilters();

        for (Container.Filter filter : getFilters()) {
            container.addContainerFilter(filter);
        }
}

The problem with the code above is that it's effectively adding "AND" filters to the container so I'm only left with the last value from the ListSelect control.
What I need is to create an OR filter that contains a Compare.Equal for every selected value

new Or(new Compare.Equal("brokerId.id", id1),new Compare.Equal("brokerId.id", id2),...)

Is there a way to create an Or filter and add to that filter when I iterate the selected values of my ListSelect control?


Solution

  • Or filter constructor can take array of filters as parameters, i.e. you can do the following:

    Filter[] filters = ...;
    String[] ids = ...;
    for (int i=0;i<10;i++) {
        filters[i] = new Compare.Equal("brokerId.id", ids[i]);
    }
    Or or  = new Or(filters);