Applying filter to datasource in controller

Is there a way to add filters to datasources from the controller code, without adding it to view?
Found the

setQueryFilter(QueryFilter filter)

method but I couldn’t figure out how to build the filter itself. Couldn’t find any documentation regarding programmatic filtering as well.

  1. Simple condition, date condition
  2. Multiple conditions (AND, OR, nesting)

I have found this but still trying to find out how to use the method…

Hi Oleg,

You can create an instance of QueryFilter and then pass it to the CollectionDatasource.setQueryFilter() method to modify the query and then call CollectionDatasource.refresh(). The QueryFilter can be created from XML (see an example here) or from a structure of LogicalCondition and Clause objects.

The same mechanism is used when you define the filter inside the query element of the controller XML. It is explained in the docs.

Hi Konstantin,
Thanks for feedback.
Found the examples for creating the


from XML in git repository, but unfortunately this is not a viable option.
On the other hand after spending quite a while on this issue, could not figure out how to actually build






Is there a ready example you can share or doc how to do that?

Here it is: GitHub - cuba-labs/query-filter: Programmatic usage of QueryFilter

The main part:

LogicalCondition orCondition = new LogicalCondition("", LogicalOp.OR);
orCondition.getConditions().add(new Clause("", " like :(?i)custom$paramValue", null, null, null));
orCondition.getConditions().add(new Clause("", " like :(?i)custom$paramValue", null, null, null));
QueryFilter queryFilter = new QueryFilter(orCondition);
customersDs.refresh(ParamsMap.of("paramValue", "%" + value + "%"));

The conditions API is not very convenient for ad-hoc usage because it was designed for generic Filter component. Could you explain in more detail why you need such programmatic filtering instead of declarative? We would like to have some motivation to improve the API.

1 Like

Konstantin, thanks a lot for support.

My main objective is (similarly to what you’ve provided in example) to apply a quick filter by adding a simple component to ButtonsPanel (in my case a checkbox). Using the generic filter is not desirable as the filtered table is a nested one, filter parameters are very basic and full-blown filter would be an overkill.

After further research and “inspiration” from sample-timesheets app I reckon declarative approach might be a viable option. The only issue I have with it is that by default CUBA doesn’t create queries for datasources & I would prefer not meddling with it in the view file, but rather sort out the filter in controller. If I understand correctly declarative approach requires building the query & the filter with parameters in view file (and adding


only without


to view would not work).
In your example though the query for Customer was included nonetheless.

That said, somehow, I was unable to implement your solution in my project correctly and would appreciate if you could help me resolve the error.

I have a many-to-many relationship Customer - CustomerStrategy - Strategy*. In customer-edit screen I would like to filter the strategies that are valid on any given date (for simplicity current date activated by checkbox) using *validFrom and validTo properties in Strategy.






        <datasource id="customerDs"
            <query><![CDATA[select c from segapp$Customer c]]></query>
            <collectionDatasource id="strategiesDs"
                <![CDATA[select cs from segapp$CustomerStrategy cs where cs.customer = :ds$customerDs]]>




         activeOnlyCheckbox.addValueChangeListener(event -> {

            if (Boolean.TRUE.equals(event.getValue())) {

                Date today = new Date();

                LogicalCondition andCondition = new LogicalCondition("", LogicalOp.AND);
                andCondition.getConditions().add(new Clause("", "cs.strategy.validFrom <= :(?i)custom$today", null, null, null));
                andCondition.getConditions().add(new Clause("", "cs.strategy.validTo >= :(?i)custom$today", null, null, null));
                QueryFilter queryFilter = new QueryFilter(andCondition);

                strategiesDs.refresh(ParamsMap.of("today", today));

            } else {



As a result I get a UnsupportedOperationException:

	at com.haulmont.cuba.web.gui.components.WebAbstractField.lambda$attachListener$6f56ebaa$1(
	at sun.reflect.GeneratedMethodAccessor126.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at com.vaadin.event.ListenerMethod.receiveEvent(
	at com.vaadin.event.EventRouter.fireEvent(
	at com.vaadin.event.EventRouter.fireEvent(
	at com.vaadin.server.AbstractClientConnector.fireEvent(
	at com.vaadin.ui.AbstractField.fireValueChange(
	at com.vaadin.ui.AbstractField.setValue(
	at com.vaadin.ui.AbstractField.setValue(
	at com.vaadin.ui.AbstractField.setValue(
	at com.vaadin.ui.CheckBox$1.setChecked(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at com.vaadin.server.ServerRpcManager.applyInvocation(
	at com.vaadin.server.ServerRpcManager.applyInvocation(
	at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(
	at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(
	at com.vaadin.server.communication.ServerRpcHandler.handleRpc(
	at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(
	at com.haulmont.cuba.web.sys.CubaVaadinServletService$CubaUidlRequestHandler.lambda$synchronizedHandleRequest$0(
	at com.haulmont.cuba.web.sys.CubaVaadinServletService.withUserSession(
	at com.haulmont.cuba.web.sys.CubaVaadinServletService$CubaUidlRequestHandler.synchronizedHandleRequest(
	at com.vaadin.server.SynchronizedRequestHandler.handleRequest(
	at com.vaadin.server.VaadinService.handleRequest(
	at com.vaadin.server.VaadinServlet.service(
	at com.haulmont.cuba.web.sys.CubaApplicationServlet.serviceAppRequest(
	at com.haulmont.cuba.web.sys.CubaApplicationServlet.service(
	at javax.servlet.http.HttpServlet.service(
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(
	at com.haulmont.cuba.web.sys.CubaHttpFilter.handleNotFiltered(
	at com.haulmont.cuba.web.sys.CubaHttpFilter.doFilter(
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(
	at org.apache.catalina.core.StandardWrapperValve.invoke(
	at org.apache.catalina.core.StandardContextValve.invoke(
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(
	at org.apache.catalina.core.StandardHostValve.invoke(
	at org.apache.catalina.valves.ErrorReportValve.invoke(
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(
	at org.apache.catalina.core.StandardEngineValve.invoke(
	at org.apache.catalina.connector.CoyoteAdapter.service(
	at org.apache.coyote.http11.Http11Processor.service(
	at org.apache.coyote.AbstractProcessorLight.process(
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(
	at java.util.concurrent.ThreadPoolExecutor.runWorker(
	at java.util.concurrent.ThreadPoolExecutor$
	at org.apache.tomcat.util.threads.TaskThread$


You cannot use neither query nor QueryFilter in a nested datasource. A nested datasource doesn’t load data itself, it just serves as a wrapper around a collection attribute of a master entity.

In order to use filtering, you can create a standalone collection datasource for CustomerStrategy and link its query to the Customer datasource using a parameter as explained here. There is another restriction though - you cannot use composition with a standalone datasource, which means your CustomerStrategy objects will be saved independently from the owning Customer. Let me know if you still need composition in this case, I’ll try to provide a solution for filtering of a nested datasource - however it won’t be straightforward.

Dear Konstantin,

Thanks again. This time it works as expected. At this moment I’m not using composition as CustomerStrategy will also have additional fields and therefore association works better.

One side-note with standalone collection datasource though : when creating a new CustomerStrategy, Customer field is not populated automatically, and Customer in question should be passed as a parameter.

Here’s sample code (in case anyone might be interested, picked up from “screen manipulation sample”):
New action in CustomerEdit controller to pass Customer as a parameter

    private Metadata metadata;

    private Datasource<Customer> customerDs;

    public void onAdd(Component source) {

        CustomerStrategy customerStrategy = metadata.create(CustomerStrategy.class);
        CustomerStrategyEdit dialog = (CustomerStrategyEdit) openEditor("segapp$CustomerStrategy.edit", customerStrategy, WindowManager.OpenType.DIALOG, ParamsMap.of("customer", customerDs.getItem()));



It works, just not sure if


is the most appropriate way to get currently selected Customer.

Picking up parameter in CustomerStrategyEdit controller and assigning it to newly created object

    private Customer customer;

    protected void initNewItem(CustomerStrategy item) {
        if(customer!=null) {

If it’s the Customer edit screen, just getItem() will also work - it returns the currently edited entity.

Also, in the standard CreateAction there is a special method for setting initial values in created entity, for example:

    protected void postInit() {
        myCreateAction.setInitialValues(ParamsMap.of("customer", getItem()));

Noted with thanks.
Appreciate your support!

Great, Query Filter is a really cool thing I was unaware before.

Hello. I have the same problem, but in my case nested datasource must be with composition. How can I create filter in this case?

composition is just a specific type of association, so there is nothing special about it in that respect. Netsed datasources cannot be filtered by their nature - they are just wrappers. You have to use a standalone datasource if you need to apply a filter (see earlier in this topic).

Thank you Ilya. I understand differences nested and standalone DS. But may be you know workaround, what fixed my problem?

Sorry, I didn’t get what exactrly your problem is.

I need filter for nested datasource… or anything else like as filter… may be programatically search from DS…

As this topic suggests, the common WA is to use a separate DS. Any reasons this doesn’t work for you?

But how said Konstantin I will have another problem because it will be not nested DS and will be problem with commit. Ok, I understand, thanks.