How to add a Checkbox to a PowerApps gallery to add or remove items to/from a collection?

Summary

I need to add a checkbox to a Vertical Gallery and allow the user to check or uncheck the checkbox to add or remove the item to a new collection.

Step 1: Add a button on a screen, and add the following code in OnSelect.

/Create a collection
ClearCollect(colVehicles,
{Id: 1,Year: 2021, Make: "Honda", Model: "CR-V"},
{Id: 2,Year: 2021,Make: "Honda",Model: "HR-V"},
{Id: 3,Year: 2020,Make: "Honda",Model: "Accord"},
{Id: 4,Year: 2020,Make: "Mazda",Model: "CX30"},
{Id: 5,Year: 2022,Make: "Mazda",Model: "CX9"},
{Id: 6,Year: 2023,Make: "Mazda",Model: "CX-5"},
{Id: 7,Year: 2016,Make: "Toyota",Model: "Camery"}
);
// Add a new "IsItemSelected" column with default "false" to a new collection.
ClearCollect ( colNewVehicles,
AddColumns(colVehicles,"IsItemSelected",false));
// Start with the blank selected collection
ClearCollect(colSelectedVehicles,Blank());

Step 2: Bind the above new “colNewVehicles” collection to a Vertical Gallery. Bind the Year, Make, and Model.

Step 3: Now add a new Checkbox to this Gallery. Add the following code to the properties of this checkbox.

In the Default property of the Checkbox set the following code:

ThisItem.IsItemSelected

In the OnCheck property of the Checkbox set the following code:

Patch (colNewVehicles, ThisItem, {IsItemSelected: true} );
Collect(colSelectedVehicles, ThisItem);

In the OnUnCheck property of the Checkbox set the following code:

Patch ( colNewVehicles, ThisItem, {IsItemSelected: false} );
RemoveIf( colSelectedVehicles, Id = ThisItem.Id );

Step 4: (Optional) Bind the above colSelectedVehicles collection to the Vertical Gallery to see which items the user selects or deselect gets added to it. See below.

Conclusion

The above tips and steps will allow you to add a check box to add or remove items to a collection.

Refer

https://learn.microsoft.com/en-us/power-platform/power-fx/reference/function-clear-collect-clearcollect

https://learn.microsoft.com/en-us/power-platform/power-fx/reference/function-patch

https://learn.microsoft.com/en-us/power-platform/power-fx/reference/function-table-shaping

Unknown's avatar

About Pankaj

I am a Developer and my linked profile is https://www.linkedin.com/in/pankajsurti/
This entry was posted in Power Apps. Bookmark the permalink.

1 Response to How to add a Checkbox to a PowerApps gallery to add or remove items to/from a collection?

  1. Jonnie's avatar Jonnie says:

    Amazing work!!!

Leave a comment