Summary
A short description of how to make something that functions like a WHILE loop in Power Apps using a button and a hidden toggle.
Picture: One Infinite Loop, Ignacio Sanz, CC BY-SA 2.0, via Wikimedia Commons and Flickr
The Problem: Power Apps only has ForAll
Loops
When I was creating a demo Power App to fetch and display Dad Jokes, one of the challenges I faced was to fit the joke text inside a speech bubble graphic. The speech bubble was expandable, but only within limits, so I needed to keep fetching jokes and checking the length of their text until I found one short enough to fit inside the bubble design.
However, looping in Power Apps turned out to be tricky. Unbelievably, I discovered there is only one kind of loop in Power Apps: ForAll
, which is used for looping over tables and collections. Power Apps really doesn’t have any other kind of loops, or even GoTos in the coding it makes available.
Making a While Loop in Power Apps
However, after much research, trial and error, I found a way to do this with just the loop (More Dad jokes) button and a hidden toggle:
Hidden Toggle ‘While’ Loop:
More Dad jokes (loop) button:
- Sets
varLoop
to false - Fetches joke
- Tests loop condition
- If loop is needed, sets varLoop to true
Toggle default:
Toggle default property is set to varLoop
Toggle onCheck:
Toggle onCheck property calls the function:
Select(more Dad jokes button)
Settings for the working WHILE loop with a Toggle
Here are the settings that worked:
Screen1.OnVisible
This is the code that goes in
Screen1.OnVisible
:Set(MaxJokeLength, 160);
Select(FetchJokeButton)
The Loop Toggle
The loopToggle control is added inside the FrameContainer. Its Default
property is set to varLoop
and its Visible
property is set to Off
so it stays hidden from view except as an outline when it is selected for editing:
The loopToggle’s OnCheck
property is set to Select(FetchJokeButton)
:
The ‘More Dad Jokes’ Button
Finally, this is the code in the OnSelect property of the ‘More Dad Jokes’ button:
Set(varLoop, false);
ClearCollect(dadJokesCollection, DadJokes.FetchARandomDadJokeJson("application/json"));
If ((Len(First(dadJokesCollection).joke) > MaxJokeLength), Set(varLoop, true));
Clicking the ‘More Dad Jokes’ button, whether manually or by automation, resets the toggle back to Off, clears the collection, fetches a new joke and adds it to the collection (of one!), tests whether the joke is too long, and if it is, it switches the toggle back on, which restarts the loop by ‘clicking’ the button again:
See more detail about this app and how the While loop works in it here…
The working result:
After removing the test code and re-testing the app, the first joke seemed very appropriate:
(One Infinite Loop, Ignacio Sanz, CC BY-SA 2.0, via Wikimedia Commons and Flickr)
Leave a Reply