Search code examples
powerapps

Set an Array Element in Power Apps


This should be easy but I can't get it to work. I'm using an array to show different datasources in a popup window. Since I can't use a variable as a datasource, I have to create 8 separate groups with their corresponding datasources in each group. My initial array is

Set(toggle_popup, [0,0,0,0,0,0,0,0,0])

then when I click the click I want the corresponding window to open. So if I want the second box (containerNum = 2) to open, in the onSelect event of my link I have

Patch(
    toggle_popup,
    Index(toggle_popup, FieldLabel.ContainerNum),
    {
        Value: 1
    }
);

I'm getting an invalid datasource error in the Patch function.

What I want is this:

toggle_popup = [0,0,1,0,0,0,0,0,0]

And the Visible property of component 2 is

If (Index(toggle_popup,2).Value = 1, true)

In regular code, all I want to do is this:

toggle_popup[FieldLabel.ContainerNum] = 1

But that doesn't seem to work.


Solution

  • In Power Apps today, if you set a table to a variable using the Set function, it is considered to be immutable - which is why you see the error in your Patch function saying that the data source is invalid. This will likely change in the near future, but for now you can define the toggle_popup variable as a collection instead:

    ClearCollect(toggle_popup, [0,0,0,0,0,0,0,0,0])
    

    or

    ClearCollect(toggle_popup, 0,0,0,0,0,0,0,0,0)
    

    That solves the first problem, but not the entire scenario. When updating local collections, the Patch function will look for the first record that matches its second argument. In your case, the first record will match Index(toggle_popup, 2) - as will all the other records, so it will update the first record instead of the second one as you want.

    You can solve this by making each record unique, using something like this:

    ClearCollect(toggle_popup, AddColumns([0,0,0,0,0,0,0,0,0], Id, GUID()))
    

    Now each record in the collection has a different value, so if this expression is executed:

    Patch(
        toggle_popup,
        Index(toggle_popup, 2),
        {
            Value: 1
        }
    );
    

    Then the second element of the collection will be updated.