We can now add User-Defined Functions to our Power Apps. Functions allow us to separate some of our business logic from the UI. It also allows us to reuse functions across the app. User-Defined Functions are now a part of Components. While Components will enable you to create reusable UI controls that are used across your apps, Functions allow you to create reusable logic used across your app.
Create a Component.
- Under Tree View, open the Components Tab.
- Click New Component.
- Rename the Component to something useful.
- Likely, this component will not have any UI. You can change the screen size to something small, say 40x40.
Enable User-Defined Functions in your Components.
Currently, the User-Defined Functions functionality of Components is experimental and needs to be enabled.
- From your app, go to File > Settings > Advanced Settings.
- Search for `component` and find Enhanced component Properties and enable it.
Create a Component Property.
- Within the Component, click New custom property.
- Display Name to something descriptive. E.g., “Calculate Mileage Reimbursement.”
- Set the Name to a short value with no spaces (or leave the default).
- The Description can be anything that describes your function.
- Set the Property Type to Output.
- Se the Data type. In this example, we are returning Currency.
- Next, create a new parameter.
- The Parameter Name must be short and have no spaces. E.g., “Mileage.”
- The Description can be anything that describes the parameter.
- The Data Type is the type of value passed. E.g., “Number.”
- Check the Required box if this parameter will be required for your function.
Define your Functions Formula.
Now we need to take our input parameters and do something with them.
- Select your component.
- From the Property Dropdown, select the Function that you created.
- In the Formula Bar, you can add your formula. In this example, we’re simply multiplying the Mileage provided from the input parameter by .06 and rounding it to two decimal places.
Use your function in the app.
Now we can use our function across our app.
- Open the screen where you want to use the function.
- From the Insert menu > Custom > Select your Component to add it to the screen.
- Rename the component that you added.
- I added a textbox for entering the mileage. Then I added a label that calls my function.
- I set the Text property of that label to `comHomeUDF.CalculateMileageReimbursement(Value(txtMileage.Text)) `
I have been using User-Defined functions in a complicated app that I have been building for a client. It really helps to separate the logic out of the controls. Especially when you need to reuse that logic in multiple places. This is another step in the right direction in enabling power users to build robust applications with low-code.