cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Anonymous
Not applicable

Custom method/function for avoiding repeated code in powerapp

Hi,

 

I have created small app based on sharepoint data.

 

App pull data from sharepoint and displayes summary using graphs and few labels. There are few actions on app screen like week filter and there is additional filter by some roles using drop downs. App also refreshes data using timer control every 5 min if app is kept running.

 

Code pulls data from 2-3 sharepoint views and manipulate data based on filters before it is displayed or everytime something changes in drop down screen values are refreshed.

 

Same code is used for Onvisible of screen, onselect in refresh icon, ontimerend in timer control and onchange in 2 drop downs.

 

Now there is duplication of codes. If i change anything i have to manually replicate code on all 5 locations on screen. Please suggest is there anyway i can simplify by writing 1 custom functions on powerapps which can be called on all 5 location. This can help me reduce errors and consistancy in reporting on screen.

 

Thanks and waiting for your reply.

 

Priyank

1 ACCEPTED SOLUTION

Accepted Solutions

Hello @Anonymous,

Yes, you are right. It should have been easier to achieve something like this.

After some testing I also confirm that:

 

"True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B."  


But maybe there is a solution. I don't know if you can use it but take a look at this..

 

Select(A);Select(B) doesn't work because the two selects are independent.
You can try Select(A);Select(A) though. This way, ButtonA is pressed the first time and it's not pressed for the second time before the code runs. So, this is an example that works.


Button1.OnSelect = 
UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,ClearCollect(Collection1,RetrieveObjectData.Run("Root"));UpdateContext({vScriptToRun:2}),
2,ClearCollect(Collection2,Collection1);UpdateContext({vScriptToRun:3}),
3,ClearCollect(Collection3,Collection2))

RetrieveObjectData is a flow that takes some time to run.
By changing the variable vScriptToRun the next select function will run different script each time.
In your case it would be..

Button1.OnSelect = UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,Script1 for Reading the first two CDS entities can be done in parallel;UpdateContext({vScriptToRun:2}),
2,Script2 for Reading the next CDS entity can only be done after the first two are complete;UpdateContext({vScriptToRun:3}),
3,Script3 for Reading the objects from Salesforce can only be done once the other step is done)

Yeah, not very nice way to do what you need but it may help.

View solution in original post

11 REPLIES 11
Mike8
Memorable Member
Memorable Member

Hello,

This might help..
https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-select

You can have the code that you repeat multiple times in the same screen, on the OnSelect property of a button, and reference the button using the Select() function

Anonymous
Not applicable

I use the button method and it works fairly well, though as mentioned you can't "call" (Select()) a button from another screen.

 

However, one thing I have tried (which works fairly well) is to use Navigate() to quickly hop to the screen with the button that has the buttons with the code I want on it, and then quickly navigate back by calling Back().  I pass parameters in the Navigate() to tell the other screen which "buttons" to press, and what to do.

 

While this seems a bit convoluted (and I agree that it is and only use this sparingly), it can be necessary in my app as I read in a lot of data from multiple sources that needs to be displayed and at times updated.  No way could I, or would I, duplicate that code everywhere it is needed.

 

This does result in a slight "flicker" of the screens (as it changes to one and back to the other), but I've lessened that by using the screen to show what is being done with some animation.  

 

Note that the issue with the button approach is that when you call a button from one code block using Select(button), that will IMMEDIATELY return so if you code that calls it relies upon the code you called to be complete - it won't be (in most cases).  ie: they are executed in parallel.  

 

No easy way around this and there aren't (to my knowledge) any functions in PowerApps to allow you to synchronize between two sections of code.  

 

You can simulate something like a semaphore (or more appropriately a "spinlock") by using a global variable and a timer.  I won't go into the details here, as it would take a while to explain.  

 

I did this initially and it worked well (though took me quite a while to work out all of the details).  However, in the end, I managed to structure my code in such a way that the synchronization wasn't needed (ie: ensured there were no dependencies on stuff the called button did the "caller" required at that point - though you cannot always do this).  

 

If only we had macros within PowerApps, that would alleviate the need for all of this mess (though honestly still some need to do synchronization for other purposes as well).

Hello BrianR,

If you need to run the expression from a different screen, as you said you need to work with the global variable and the timer.
If you haven't done it yet, you can also have variables in the expression that you set to the desired value before you run the expression and they are used like parameters. You can have the functionality but it could have been easier.
I think this is the issue. 🙂

Edit: I have just tested on what you said here
"Note that the issue with the button approach is that when you call a button from one code block using Select(button), that will IMMEDIATELY return so if you code that calls it relies upon the code you called to be complete - it won't be (in most cases).  ie: they are executed in parallel."
and I now understand your problem. Yes. I was expecting to run the expression differently.
I tried
Button1.OnSelect = Collect(A,{text:"A"})
Button2.OnSelect = Select(Button1);Select(Button1);Collect(A,{text:"B"})
I pressed Button2 and instead of A,A,B the table is B,A,A.
Strange.

Edit 2:
When I tried it like this, by pressing Button3
Button1.OnSelect = Collect(A,{text:"A"})
Button2.OnSelect = Collect(A,{text:"B"})
Button3.OnSelect = Select(Button1);Select(Button2);Select(Button1);Select(Button2);Select(Button1);Select(Button2)
it worked as expected.
You may need to have only the Select() functions on the pressed button. No extra expressions. 
Seems like when there are extra expressions, the code runs like using the Concurrent() function. And when not, it run as you expect.
I did a quick test. I don't know how reliable it is. You can try it though.


v-xida-msft
Community Support
Community Support

Hi @Anonymous,

 

Could you please share a bit more about your scenario?

Do you want to use 1 custom function in all 5 locations on your screen instead of the repeated code? 

Further, could you please show more details about the repeated code within your app?

 

If the repeated code that you mentioned is used to retrieve the data from your SP list data source and manipulate data based on filters, you could consider take a try to create a collection (Using ClearCollect function) to store the filter data/results, then if you want to reference the filtered data/results in other location, you could reference the collection directly.

 

In addition, I also agree with @Mike8's thought almost. If you have same action formula within the OnSelect property of other controls, you could consider take a try to use the Select function to achieve your needs. But please make sure all controls (which has same action formula, e.g. ) are within same container.

 

Best regards,

Kris

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Anonymous
Not applicable

@Mike8,

 

The reason for the timer is that I need one of the "functions" (aka buttons) to wait on another to complete.  I do indicate completion by a global variable that one sets and the other checks, but there is no way to have the other one wait on that variable to be set that I'm aware of other than using a timer (set the timer that autoresets to timeout say after 250ms and then call itself.  if the flag is not set, then don't do anything within the button, if it is, then stop the timer and continue the code that was dependent on the first to be complete).

 

True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B.  

 

But if you have something short that executes quickly, then I imagine in many cases the action behind A might be done before the action behind B.  But probably also not guanteed unless PowerApps is specifically looking for this and then serializing things.

 

I do know though that when you have a lot of code in the OnSelect for a button, that you cannot guarantee that the action for Select(A) is done before the action behind Select(B) (yes you can ensure that A is pressed/selected before B, but not that one will complete before the other).  🙂  

 

 

In my case, the code behind each button takes a while to execute (2-3 seconds usually) as it is loading multiple data sources and doing some filters (3 CDS entities, 5 Salesforce objects).  So in this case I've seen this happen all over the board regarding what gets done first (and no consistent pattern, which makes sense).  

 

The only way I know that easily works for this is to have the first call Navigate() back to the same screen, passing that screen data telling it to start the 2nd.  🙂  (which is an "easy" workaround but causes even more flicker on the screen so the timer approach is perhaps slightly better (though it technically is "slower" within the resolution of your timer).  

 

Honestly, while it was nice to see the Concurrent() function and it does make some things easier - technically it wasn't needed as with Select() you could do the same thing.  What we need is something that allows for sequetial execution - either macros or true functions (either) or a synchronization object that I can wait on.  🙂

 

But your point about "You can have the functionality but it could have been easier" is indeed the issue - not just with this - but with most everything in PowerApps.  ie: I want to have the user upload an image of any resolution with the Add Picture control (works), display it in an Image control (works) and then upload it to CDS.  

 

Hmm, well, yes I can upload it as an entity image, but that is limited to 144x144 ( and it crops the image so if it was rectangular, its a mess).  To upload in full detail - well you have to use a Flow, Azure function, etc.  Why?  

 

Things like these where basic functionality (like macros, or a wait function, ability to upload files to Sharepoint, open Excels from Sharepoint, upload images in full resolution, etc) that one would expect to be in PowerApps but isnt - really moves this out of being a tool for non developers to one giving a developer headaches.  😞

 

 

Anonymous
Not applicable

Hi Kris,

 

So basically all I really want to do in this case is reuse code in multiple sections of my app.  There are MANY scenarios for this - from just basic logic that might implement an equivalent filter within galleries on the same or different screen, to perhaps a debug macro that will log to a collection ie: DebugMessage( "Operation successful", Success) which would do a Collect( ) to set various parameters (think of an event log), etc.  

 

Without the ability to do a macro, I'm duplicating that code in MANY places.  In the event log example I have to duplicate lines such as:

 

 

If(gDbgEnabled, Collect( cAppLog, { Scrn:LogName, Obj: "Test", 
             Msg: "Test message", Time: Now(), LogLvl: LogLvl.Info } ) );

 

in my code to do this - this basically will only update the collection (maintain the log) if my gDbgEnabled variable is true, but it also formats the message and adds other parameters.  Which other than it being a lot to type and paste, also is MUCH harder to maintain (what if I wanted to change something about the format of how this was put into the log (collection)?  I'd have to change it EVERYWHERE it was used.

 

With a macro, I could instead define a macro in such a way that I could call it instead like:

 

Debug( "Test", "Test message", LogLvl.Info )

and have it be replaced by the code above (I'm thinking "C" type macros here for reference).  With the ability to define a function within PowerApps - even better.  Each of which is FAR more maintainable, and for that matter easier to understand, and leads to LESS potential for errors.  And having the ability for the macros to be called between screens makes that even better.

 

 

But in the case that I was using Select(), its more pronounced.  I am loading from 8 data sources - 3 from CDS and 5 from Salesforce into separate collections (the CDS ones I'm reading multiple records, the Salesforce onces, only a single record per object).

 

Two of the CDS entities have no direct dependence on the other being loaded, but the third has LookUps() to the first two so I need to make sure that they are loaded first (I'm doing a LookUp() to the Collection they were loaded into, not back to the data source).  

 

The Salesforce objects I then read in are mostly independent of each other.

 

So basically I need to ensure that the following is sequentially done:

 

  • Reading the first two CDS entities can be done in parallel
  • Reading the next CDS entity can only be done after the first two are complete
  • Reading the objects from Salesforce can only be done once the other step is done

 

 

Note that these aren't simple ClearCollect()s to load the data, but each item loaded has multiple filters on it, in some cases is calling AddColumns(), and other data transformations as it brings it into the respective collections.  Also multiple conditions on what load in based on various criteria.  

 

The reason I don't just put all of this in a big code block and forget about it is that I give the user the option to Refresh and reload the CDS entities at any time and do not wish to duplicate this code and maintain it separately.   Ditto with the items from Salesforce.  

 

The CDS entities SHOULD in most cases not HAVE to be reloaded as they seldom change (mostly static data), though the collections loaded from Salesforce can't all be loaded at once (there are over 200,000 records and I only need 1) and throughout the application, the user might choose another.  

 

But in both cases, the user needs the ability to refresh the info at will and independently of each other.

 

Not sure how else to do this.  Since there is no direct way to share code or do macros, the Select() "hack" (potentially having to Navigate() between screens) is the "best" approach I know of being available (similar to how a boat makes the "best" airplane out of a list of boat, anchor, and bag of cement.  :-))  

 

Having either Macro or true Function capability - or a "WaitFor" function would resolve either (Macro/Function is the right approach here though, but "WaitFor" has other uses).

 

Lack of Macro support or function) is my #1 issue with PowerApps.  And while calling out to MS Flow, Azure, or third party web service is possible to do some of this - it is both something that SHOULD be unnecessary - but also won't work in all cases well.  And of course - taking Flow as an example - having to use a separate tool using a different language to do basically functionality that should be provided just complicates what is supposed to be (PowerApps) an easy "no code" (or low code) environment to build applications into something involving more skills and components than necessary.

 

Hello @Anonymous,

Yes, you are right. It should have been easier to achieve something like this.

After some testing I also confirm that:

 

"True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B."  


But maybe there is a solution. I don't know if you can use it but take a look at this..

 

Select(A);Select(B) doesn't work because the two selects are independent.
You can try Select(A);Select(A) though. This way, ButtonA is pressed the first time and it's not pressed for the second time before the code runs. So, this is an example that works.


Button1.OnSelect = 
UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,ClearCollect(Collection1,RetrieveObjectData.Run("Root"));UpdateContext({vScriptToRun:2}),
2,ClearCollect(Collection2,Collection1);UpdateContext({vScriptToRun:3}),
3,ClearCollect(Collection3,Collection2))

RetrieveObjectData is a flow that takes some time to run.
By changing the variable vScriptToRun the next select function will run different script each time.
In your case it would be..

Button1.OnSelect = UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,Script1 for Reading the first two CDS entities can be done in parallel;UpdateContext({vScriptToRun:2}),
2,Script2 for Reading the next CDS entity can only be done after the first two are complete;UpdateContext({vScriptToRun:3}),
3,Script3 for Reading the objects from Salesforce can only be done once the other step is done)

Yeah, not very nice way to do what you need but it may help.

Anonymous
Not applicable

@Mike8 - That's actually a great idea to use the two back to back Selects of the same button.  I'll try that!  Hadn't thought of this, but it makes sense.  Definitely a kludge, but one that looks to be very workable.   I'll try this when I have time.

 

I've already used the parameters to the screen in the way you mentioned, and it works well other than having to change the user's view (for however long the actions take).  But not too bad.  

 

Thanks,
Brian

Anonymous
Not applicable

Selects only add the action to the queue. So if you queue it right, it will follow that sequence. But other user actions might still come in between. Let's just put the Function definition as soon as possible into the tool.

Helpful resources

Announcements

Community will be READ ONLY July 16th, 5p PDT -July 22nd

Dear Community Members,   We'd like to let you know of an upcoming change to the community platform: starting July 16th, the platform will transition to a READ ONLY mode until July 22nd.   During this period, members will not be able to Kudo, Comment, or Reply to any posts.   On July 22nd, please be on the lookout for a message sent to the email address registered on your community profile. This email is crucial as it will contain your unique code and link to register for the new platform encompassing all of the communities.   What to Expect in the New Community: A more unified experience where all products, including Power Apps, Power Automate, Copilot Studio, and Power Pages, will be accessible from one community.Community Blogs that you can syndicate and link to for automatic updates. We appreciate your understanding and cooperation during this transition. Stay tuned for the exciting new features and a seamless community experience ahead!

Summer of Solutions | Week 4 Results | Winners will be posted on July 24th

We are excited to announce the Summer of Solutions Challenge!   This challenge is kicking off on Monday, June 17th and will run for (4) weeks.  The challenge is open to all Power Platform (Power Apps, Power Automate, Copilot Studio & Power Pages) community members. We invite you to participate in a quest to provide solutions in the Forums to as many questions as you can. Answers can be provided in all the communities.    Entry Period: This Challenge will consist of four weekly Entry Periods as follows (each an “Entry Period”)   - 12:00 a.m. PT on June 17, 2024 – 11:59 p.m. PT on June 23, 2024 - 12:00 a.m. PT on June 24, 2024 – 11:59 p.m. PT on June 30, 2024 - 12:00 a.m. PT on July 1, 2024 – 11:59 p.m. PT on July 7, 2024 - 12:00 a.m. PT on July 8, 2024 – 11:59 p.m. PT on July 14, 2024   Entries will be eligible for the Entry Period in which they are received and will not carryover to subsequent weekly entry periods.  You must enter into each weekly Entry Period separately.   How to Enter: We invite you to participate in a quest to provide "Accepted Solutions" to as many questions as you can. Answers can be provided in all the communities. Users must provide a solution which can be an “Accepted Solution” in the Forums in all of the communities and there are no limits to the number of “Accepted Solutions” that a member can provide for entries in this challenge, but each entry must be substantially unique and different.    Winner Selection and Prizes: At the end of each week, we will list the top ten (10) Community users which will consist of: 5 Community Members & 5 Super Users and they will advance to the final drawing. We will post each week in the News & Announcements the top 10 Solution providers.  At the end of the challenge, we will add all of the top 10 weekly names and enter them into a random drawing.  Then we will randomly select ten (10) winners (5 Community Members & 5 Super Users) from among all eligible entrants received across all weekly Entry Periods to receive the prize listed below. If a winner declines, we will draw again at random for the next winner.  A user will only be able to win once overall. If they are drawn multiple times, another user will be drawn at random.  Individuals will be contacted before the announcement with the opportunity to claim or deny the prize.  Once all of the winners have been notified, we will post in the News & Announcements of each community with the list of winners.   Each winner will receive one (1) Pass to the Power Platform Conference in Las Vegas, Sep. 18-20, 2024 ($1800 value). NOTE: Prize is for conference attendance only and any other costs such as airfare, lodging, transportation, and food are the sole responsibility of the winner. Tickets are not transferable to any other party or to next year’s event.   ** PLEASE SEE THE ATTACHED RULES for this CHALLENGE**   Week 1 Results: Congratulations to the Week 1 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Community MembersNumber of SolutionsSuper UsersNumber of Solutions @anandm08  23 @WarrenBelz  31 @DBO_DV  10 @Amik  19 AmínAA 6 @mmbr1606  12 @rzuber  4 @happyume  7 @Giraldoj  3@ANB 6 (tie)   @SpongYe  6 (tie)     Week 2 Results: Congratulations to the Week 2 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Community MembersSolutionsSuper UsersSolutions @anandm08  10@WarrenBelz 25 @DBO_DV  6@mmbr1606 14 @AmínAA 4 @Amik  12 @royg  3 @ANB  10 @AllanDeCastro  2 @SunilPashikanti  5 @Michaelfp  2 @FLMike  5 @eduardo_izzo  2   Meekou 2   @rzuber  2   @Velegandla  2     @PowerPlatform-P  2   @Micaiah  2     Week 3 Results: Congratulations to the Week 3 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Week 3:Community MembersSolutionsSuper UsersSolutionsPower Apps anandm0861WarrenBelz86DBO_DV25Amik66Michaelfp13mmbr160647Giraldoj13FLMike31AmínAA13SpongYe27     Week 4 Results: Congratulations to the Week 4 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Week 4:Community MembersSolutionsSuper UsersSolutionsPower Apps DBO-DV21WarranBelz26Giraldoj7mmbr160618Muzammmil_0695067Amik14samfawzi_acml6FLMike12tzuber6ANB8   SunilPashikanti8

Check Out | 2024 Release Wave 2 Plans for Microsoft Dynamics 365 and Microsoft Power Platform

On July 16, 2024, we published the 2024 release wave 2 plans for Microsoft Dynamics 365 and Microsoft Power Platform. These plans are a compilation of the new capabilities planned to be released between October 2024 to March 2025. This release introduces a wealth of new features designed to enhance customer understanding and improve overall user experience, showcasing our dedication to driving digital transformation for our customers and partners.    The upcoming wave is centered around utilizing advanced AI and Microsoft Copilot technologies to enhance user productivity and streamline operations across diverse business applications. These enhancements include intelligent automation, AI-powered insights, and immersive user experiences that are designed to break down barriers between data, insights, and individuals. Watch a summary of the release highlights.    Discover the latest features that empower organizations to operate more efficiently and adaptively. From AI-driven sales insights and customer service enhancements to predictive analytics in supply chain management and autonomous financial processes, the new capabilities enable businesses to proactively address challenges and capitalize on opportunities.    

Updates to Transitions in the Power Platform Communities

We're embarking on a journey to enhance your experience by transitioning to a new community platform. Our team has been diligently working to create a fresh community site, leveraging the very Dynamics 365 and Power Platform tools our community advocates for.  We started this journey with transitioning Copilot Studio forums and blogs in June. The move marks the beginning of a new chapter, and we're eager for you to be a part of it. The rest of the Power Platform product sites will be moving over this summer.   Stay tuned for more updates as we get closer to the launch. We can't wait to welcome you to our new community space, designed with you in mind. Let's connect, learn, and grow together.   Here's to new beginnings and endless possibilities!   If you have any questions, observations or concerns throughout this process please go to https://aka.ms/PPCommSupport.   To stay up to date on the latest details of this migration and other important Community updates subscribe to our News and Announcements forums: Copilot Studio, Power Apps, Power Automate, Power Pages

Users online (802)