Approval Type Automation in PowerApps
Yesterday, one of my LinkedIn connections asked me to help with a business scenario:
Business Scenario
The scenario involved two fields in a Business Process Flow:
- Approval Type (optionset)
- Approved By (systemuser lookup)
If Approval Type is set to "Approved," the Approved By field should automatically set its value to the current logged-in user.
Implementation in PowerApps Model-Driven App
You can achieve this functionality using a combination of JavaScript and event handlers. Here's how:
Steps to Implement:
- Create a JavaScript Web Resource:
- Go to Solutions in the PowerApps Maker portal.
- Add a JavaScript web resource to your solution.
- Write JavaScript code to check the value of the
Approval Typefield and set theApproved Byfield to the current logged-in user.
- Add the Script to the Form:
- Open the entity form where the
Approval TypeandApproved Byfields exist. - Go to Form Properties.
- Add the JavaScript web resource you created to the form.
- Open the entity form where the
- Add an Event Handler:
- In the same Form Properties, go to the Event Handlers section.
- Attach the
setApprovedByOnApprovalTypeChangefunction to theOnChangeevent of theApproval Typefield. - Ensure you pass the
executionContextto the function.
- Publish Customizations:
- After adding the event handler, save and publish the form.
Sample Code Snippet
function setApprovedByOnApprovalTypeChange(executionContext) {
var formContext = executionContext.getFormContext();
// Get the value of the Approval Type field
var approvalType = formContext.getAttribute("approvaltype").getValue(); // Replace 'approvaltype' with your field's schema name
// Check if Approval Type is "Approved" (value may vary based on your option set)
if (approvalType === "Approved") { // Replace with the correct option value for "Approved"
// Get the current logged-in user
var currentUserId = Xrm.Utility.getGlobalContext().userSettings.userId;
var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName;
// Set the Approved By field
formContext.getAttribute("approvedby").setValue([
{
id: currentUserId,
entityType: "systemuser",
name: currentUserName
}
]);
} else {
// Clear the Approved By field if Approval Type is not "Approved"
formContext.getAttribute("approvedby").setValue(null);
}
}