Search code examples
filtermodelodatasapui5sap-fiori

Filtering a model in FIORI leads to "f.forEach is not a function"


I am trying to read a model with a filter:

         var oFilter = new sap.ui.model.Filter({
            filters: [
                new sap.ui.model.Filter({
                    path: 'attr1',
                    operator: sap.ui.model.FilterOperator.EQ, 
                    value1: value
                }),
                new sap.ui.model.Filter({
                    path: 'attr2', 
                    operator: sap.ui.model.FilterOperator.EQ,
                    value1: value2
                })
            ], 
            and: true
        });

        model.read("/pathToEntitySet", 
            {
                success: function(oData, response) {
                    console.log("i am here");
                },
                error: function(oError){
                    console.log(oError);
                },
                filters: oFilter
            }
        );

However, I am always getting "f.forEach is not a function" when I add filters: oFilter to the model.read operation.

I am using FF 68.5.

Any ideas where this error could be coming from?


Solution

  • filters expects an array. You passed a single object. Two options:

    Option A: Drop the wrapper

    When applying multiple filters with different paths, AND is automatically assumed. So you can simply do

    const aFilter = [
        new sap.ui.model.Filter({
            path: 'attr1',
            operator: sap.ui.model.FilterOperator.EQ, 
            value1: value
        }),
        new sap.ui.model.Filter({
            path: 'attr2', 
            operator: sap.ui.model.FilterOperator.EQ,
            value1: value2
        })
    ];
    
    model.read("/pathToEntitySet", {
        success: ...
        error: ...
        filters: aFilter 
    });
    

    Option B: Add another wrapper

    Leave your filter as is and just put brackets around oFilter when passing it to filters:

    model.read("/pathToEntitySet", {
        success: ...
        error: ...
        filters: [oFilter]
    });