How to clear a collection inside ForAll in PowerApps Canvas apps

It’s been a long time I have written a blog on Canvas apps. So I made sure I start it back with a rather simple but interesting one.

The function Clear or ClearCollect cannot be invoked within ForAll.

Have you ever received the above error? If yes then you are on the right blog.

The stuff that I shall discuss here is rather a common requirement. Many a times we need to declare a temporary collection inside a ForAll statement and then utilize the collection. Once the collection is utilized, the collection will be cleared.

Let’s take a sample formula here

ForAll(
    SampleItems As Sequence,
    If(
        Sequence.Name = "",
        Clear(TempColl),
        Collect(
            TempColl, 
            Filter(
                Contacts, 'First Name' = Sequence.Name
            )
        )
    )
)
        

What I am doing in this piece of code? I am looping through a collection SampleItems and within each loop I am creating another collection TempColl where I am storing the list of contacts whose First Name match the name property of the corresponding SampleItems record.

But there is a problem. We need to clear the collection. But unfortunately we can’t use either Collect or ClearCollect. Precisely you will get the below error.

The function Clear or ClearCollect cannot be invoked within ForAll.

Then what to use? Well, we can use the wonderful RemoveIf function. We modify the formula as below.

ForAll(
    SampleItems As Sequence,
    If(
        Sequence.Name = "",
        RemoveIf(TempColl, true),
        Collect(
            TempColl, 
            Filter(
                Contacts, 'First Name' = Sequence.Name
            )
        )
    )
)
        

And cool! It has solved our problem.

Hope this helped!

Debajit Dutta
Business Solutions MVP

1 thought on “How to clear a collection inside ForAll in PowerApps Canvas apps”

Comments are closed.