Monday, July 13, 2020

Dynamics 365: Set Lookup Field To Current User on Selection of an OptionSet using JavaScript

Approval Type Scenario

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:

  1. 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 Type field and set the Approved By field to the current logged-in user.
  2. Add the Script to the Form:
    • Open the entity form where the Approval Type and Approved By fields exist.
    • Go to Form Properties.
    • Add the JavaScript web resource you created to the form.
  3. Add an Event Handler:
    • In the same Form Properties, go to the Event Handlers section.
    • Attach the setApprovedByOnApprovalTypeChange function to the OnChange event of the Approval Type field.
    • Ensure you pass the executionContext to the function.
  4. 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);
    }
}

        

Power Automate Optimization: Filter Rows vs Trigger Conditions - When and Why to Use Each

Filter Rows vs Trigger Conditions in Power Automate Filter Rows vs Trigger Conditions in Power Automate Why your flow...