6 Use-Cases For The Power Apps App Formulas Property (Named Formulas)
Power Apps named formulas enable us to use the same app logic in several different places. Unlike a variable, named formulas do not store values in memory. They recalculate each time they are referenced. Named formulas ensure the most current value is always available and up-to-date and their definition can only be managed in one-central location. In this article, I will explain the benefits of using Power Apps named formulas and show you the best ways to use them.
Table of Contents
1. Pre-Filtering SharePoint Lists
2. Gathering Extended User Profile Data
3. Checking Security Roles For The Current User
4. Obtaining URL Parameters And Setting Default Values
5. Making Simpler References To Environment Variables
6. App Theming Values (Colors & Fonts)
1. Pre-Filtering SharePoint Lists
Create a Power Apps named formula when a SharePoint list has a common set of filters used in many places. In the example below, the Service Vehicles SharePoint list has several trucks which are either active (in service) or inactive (not in service).
Service Vehicles SharePoint List:
ID | Title | Active |
1 | Service Truck 001 | No |
2 | Service Truck 002 | Yes |
3 | Service Truck 003 | No |
4 | Service Truck 004 | Yes |
5 | Service Truck 005 | Yes |
Suppose we only the active vehicles to show in Power Apps. Therefore, we write a named formula in the App Formulas property like this:
// FILTER ACTIVE SERVICE VEHICLES
fxServiceVehiclesActive = Filter(
'Service Vehicles',
Active.Value = "Yes"
)
Now we can use our named formula in the app. Write fxServiceVehiclesActive in the Items property of a gallery and only these rows will appear.
ID | Title | Active |
2 | Service Truck 002 | Yes |
4 | Service Truck 004 | Yes |
5 | Service Truck 005 | Yes |
2. Gathering Extended User Profile Data
Named formulas may be used to hold constants – a value that cannot be changed when the app is in play mode. User profile data for the current app user is an example of a constant.
We can use the Office365Users connector to get the full account details for an app user and reference it in a named formula. Whereas the User function only retrieves the account’s full name, email and image.
To do this, add the Office365Users connector to the app.
Then use these named formulas in the App Formulas property to prevent multiple calls to the Office365Users API. Once the function executes its result will be cached.
// USER PROFILE INFO
fxCurrentUser = Office365Users.MyProfile();
fxCurrentUserPhoto = If(
Office365Users.UserPhotoMetadata(fxCurrentUser.UserPrincipalName).HasPhoto,
Office365Users.UserPhotoV2(fxCurrentUser.UserPrincipalName)
);
3. Checking Security Roles For The Current User
An app design might have require us to give a user with the custom security role ” Contoso Manager “security role access to a hidden screen. To get the security roles applied add these Dataverse Users and Security Roles tables to the app.
The write this code in the app Formulas property.
// SECURITY ROLES
fxSecurityRoles = LookUp(
Users,
domainname = User().Email
).'Security Roles (systemuserroles_association)'.Name;
fxIsUserManager = "Contoso Manager" in fxSecurityRoles.Name;
Let’s supposed the named formula fxSecurityRoles returns these values.
Name |
Basic User |
Contoso Manager |
Environment Maker |
We can use the subsequent named formula fxIsUserManager to check if the current user is a manager. Since “Contoso Manager” was found in the user’s security roles the named formula returns true.
true
4. Obtaining URL Parameters And Setting Default Values
URL parameters can be passed into PowerApps and captured using the Param function. It is useful to store them in named formulas as constants because we can provide default values for when the parameter is missing.
Assume we wrote the following code in the Power Apps app Formulas property.
// URL PARAMETERS
fxUrlParameter = {
RecordId: Param("recordid"),
LaunchSource: Coalesce(Param("launchsource"), "Unknown"),
DebugMode: And(
Not(IsBlank(Param("debugmode"))),
Lower(Param("DebugMode"))="true"
)
}
Then we used this URL to access the app:
https://apps.powerapps.com/play/e/89c16fac-7c8a-e73a-bdad-f06eda01df1b/a/407a9220-3548-4b2d-9a1c-e3fda1c6b3cc?tenantId=f1b8b509-50a4-4a5c-8e48-bf3d3e7c10ed&sourcetime=2023-08-13%2001%3A28%3A13Z&recordid=1
The named formula fxUrlParameter would return these values:
- fxUrlParameters.RecordId =1
- fxUrlParameters.LaunchSource = “Unknown”
- fxUrlParameters.DebugMode = false
5. Making Simpler References To Environment Variables
Retrieving environment variables values is absurdly obtuse. We can use named formulas to abstract away the lengthy code needed to do it and use a much shorter reference instead.
Add the Dataverse tables called Environment Variable Definitions and Environment Variable Values to the app.
Then write this code in the App Formulas property.
// ENVIRONMENT VARIABLES
fxEnvironmentVariable = {
AdminEmail: LookUp(
'Environment Variable Values',
'Environment Variable Definition'.'Display Name' = "Admin Email"
).Value,
CompanyName: LookUp(
'Environment Variable Values',
'Environment Variable Definition'.'Display Name' = "Company Name"
).Value,
EnvironmentName: LookUp(
'Environment Variable Values',
'Environment Variable Definition'.'Display Name' = "Environment Name"
).Value
};
Now we are able to get the AdminEmail environment variable by simply typing
fxEnvironmentVariable.AdminEmail
6. Configuring App Theming Values (Colors & Fonts)
Named formulas make referencing theming values more convenient because we can type a friendly-text name as opposed to a color code. The fxColor formula holds a set of colors to be used in the app while fxFont formula defines fonts and text sizes.
// COLORS
fxColor = {
// Named Color Values
Danger: ColorValue("#dc3545"),
Info: ColorValue("#0dcaf0"),
Primary: ColorValue("#0d6efd"),
Secondary: ColorValue("#6c757d"),
Success: ColorValue("#198754"),
Warning: ColorValue("#ffc107"),
// Default Colors Values
Blue: ColorValue("#0d6efd"),
Indigo: ColorValue("#6610f2"),
Purple: ColorValue("#6f42c1"),
Pink: ColorValue("#d63384"),
Red: ColorValue("#dc3545"),
Orange: ColorValue("#fd7e14"),
Yellow: ColorValue("#ffc107"),
Green: ColorValue("#198754"),
Teal: ColorValue("#20c997"),
Cyan: ColorValue("#0dcaf0"),
White: ColorValue("#ffffff"),
Grey: ColorValue("#6c757d"),
GreyDark: ColorValue("#343a40"),
// Grey-Shade Color Values
Grey100: ColorValue("#f8f9fa"),
Grey200: ColorValue("#e9ecef"),
Grey300: ColorValue("#dee2e6"),
Grey400: ColorValue("#ced4da"),
Grey500: ColorValue("#adb5bd"),
Grey600: ColorValue("#6c757d"),
Grey700: ColorValue("495057"),
Grey800: ColorValue("#343a40"),
Grey900: ColorValue("#212529")
};
// FONTS
fxFont = {
Heading: Font.'Lato Black',
Body: Font.Lato,
Size: {
Body: 12,
Subtitle: 14,
Title: 16
},
LineHeight: 1.5
}
Did You Enjoy This Article? 😺
Subscribe to get new Power Apps articles sent to your inbox each week for FREE
Questions?
If you have any questions or feedback about 6 Use-Cases For The PowerApps App Formulas Property (Named Formulas) please leave a message in the comments section below. You can post using your email address and are not required to create an account to join the discussion.
I love this.
Darren,
My man. I’m glad you liked it ❤️
See you soon at MPPC 2023 😊
I can see the usefulness of something like the filter expression but I don’t understand how most of the examples are different from just setting a variable in OnStart.
Joe,
The OnStart property is being eliminated from Power Apps. To future-proof formulas should be used instead.
Using OnStart is something I avoid because it delays loading of the app. Formulas are better because data is retrieved on demand.
If you have formulas to run immediately upon opening the app, what would you use instead of OnStart❓
For instance, my app checks the office365 user profile info, then queries a user table, then an apps roles table to see what system they have access to, which roles they have, and what permission levels they have . It essentially connects part of a multi-system user management system. I hope this makes sense.
You could use named formulas to do the same. Or place the formulas in OnVisible of your Startscreen (you can define a startscreen in your app properties).
What’s the difference with the App’s Start property?
Ben,
OnStart runs before the first screen loads. Formulas run on demand.
FYI, the OnStart property is being removed from Power Apps.
Great, thanks for this post, Matthew! I wasn’t aware of this before and it would have reduced complexity for my last project a lot 😉
Just one question – is it possible to pass parameters so that formulas could be used as function? Didn’t find this in MS Learn… Best regards, Ihno
Ihno,
Passing parameters to functions is in the roadmap but it is not available at this time. I do not know the timeline for it.
Hi Matthew,
In the intro you said “Unlike a variable, named formulas do not store values in memory. ” but in number two, you said “Once the function executes its result will be cached.”
Could you elaborate on this?
Thanks!
Personally I use it to create dynamic tabs on a form.
This allows me to use the new modern TabList control. I add a ” * ” to the end of the tab name if one of the displayed cards has an error (! IsBlank(cardName.Error) in Or() function) when submitted.
It is also possible to directly display the tab where there is an error by filtering on the first “*” in the items of the TabList.
I hope I have been clear 😅
Matt. We’ve creating global variables on a dedicated start screen in place of App.OnStart because it is being deprecated. Would you still recommend using fxColorTheme vice gblColorTheme. Is there another reason to move this into formulas? Thanks again Matt. I love what you do.
This is very useful when a recalculation is needed, like the example with “Filter” as it will reload the list, contrary to a global collection variable. As for the other examples I will stick to create global vars in the initial screen (if they are empty) for now. Thanks for sharing!
Gianluca,
You’re welcome, and thanks for sharing your tip here!
Hi Matthew, I’m working on cleaning out the OnStart for production app. Simple contants were low hanging fruit, but what about something like this where a flow is being run? Works perfectly fine using Set()…
Troy,
It is not possible to use some functions such as “Run” in Named Formulas.
Thanks, Matt. If apps are moving towards deprecating OnStart, this seems like something that would need to be addressed…
Troy,
I will need to re-write so many articles…
🙂
Hi Troy, the alternative is to place these formulas into OnVisible of your Startscreen. You can define your startscreen in the App-property StartScreen.
Thanks, Niels.
Hi Matthew
you are missing a closing parenthesis on the example provided in “4. Obtaining URL Parameters And Setting Default Values” and specifically in line: Not(IsBlank(Param(“debugmode”)),
which should be
Not(IsBlank(Param(“debugmode”))),
Keep up the good work
Steak,
Fixed. Thanks for reporting the error and making my blogs better.
Hi Matthew
I am trying to use a function to create a collection but it is throwing an error. The code is as follows:
SharepointDataFormula = { //formula name
ClearCollect( //create collection from projects sp list
colProjects, //collection name
ShowColumns(
Projects_1, //sharepoint list name
“ProjectManager”, //columns to collect
“ProjectName”,
“ProjectCode”,
“listname”,
“ReportOn”,
“Title”
)
)
}
Any idea why this may be?
Best regards
Hi Matthew
Incredible coincidence that Shane Young did a video on this today. From that I deduced what the problem was, the working code is as follows:
SharepointDataFormula = Projects_1;
Doh!
BCG,
Shane is an amazing content creator. If we did post on the same topic that day I love it.
I am not sure if I am missing something or not
Shouldn’t this…
be
i.e. Without the curly braces
I got an error while placing the curly braces
Brian,
Updated. Correct. It is a table, not a record.
I want to use a named formula to get pre-filtered data from a Dataverse table to avoid delegation issues.
1) In the gallery for the remaining data not all fields show values when using the named formula as a source reference even though I see values in the Dataverse table.
2) Additional operations (comparing email of logged in user with email of created by still show delegation warning – here i thought the named formula would bring in all data and avoid delegation, same to what we see with Collections?
Am I missing something? Thanks a lot
Carsten,
Have you tried using a Dataverse view to solve these problems? If it’s pre-filtered then Views can solve delegation issues because they don’t have that limitation.
I’m currently still using OnVisible on the homepage (so I don’t have to use App.OnStart) to define constants (colors, fonts, user properties) that don’t change while the app is running. Should this definition also be made via App Formulas in the future? Are there differences in performance?
Enrico,
I define my styles in the App Formulas. I’m unsure about the performance vs. OnVisible. To me it just makes more sense to put code that is used globally in App Formulas as opposed to declaring it on the first app screen.
Hi Matthew, curious on how Named Formulas work, specifically for storing tables. Say, a variable nf_var (a table) is defined in App.Formula
Will it be two requests? I am just being conscious of which will have fewer requests VS ClearCollect. As far as I know, ClearCollect stores the table locally the first time it was executed.
Hi Matthew,
I really like the concept of using formulas and I appreciate the information you are providing here.
But now and then I get an error while using formulas.
The formula itself works and creates a table, as you can see in the screenshot,
But sometimes an error is shown, that says:
“Incompatible Types for Comparison. These types can’t be compared: Invalid, Text”
when I edit the formula, e.g. remove a quotation mark and put it back again, the error is vanished. But it’s annoying, when the App now and then shows an error.
Is this a bug, or can I do something to avoid this error?
Best regards,
Stefan.
Hi Matthew,
I have 4 spots in my powerapp where I am calling a power automate flow that gets data from a power bi query step, returns it to the app and then Parse json is used to create multiple collections that will be used in the app. Is it possible to create a reusable function for this logic? The user email needs to be passed to the power automate flow and there are spots in the app where admins can impersonate a user as well.