How To Show An Alert Based On Existing Fields In Model-Driven Apps [Solution Sunday #7]

How To Show An Alert Based On Existing Fields In Model-Driven Apps [Solution Sunday #7]

In this episode of Solution Sunday, I will show you how you can notify your users if they're interacting with a record which contains specific data.

Case Study

We have our Contact table that we use to hold records of our users who want to be put onto exercise programmes.

Users of the Model-Driven App have said that they need to see straight away if the Contact is a smoker so they can be put on the correct programme.

We currently have 3 fields with different data types that we can use to determine if the Contact is a smoker or not:

  1. Smoker (Boolean)
  2. Smoked Per Day (Whole Number)
  3. Additional Details (Lookup)


We will use Power Apps' built in 'Notification' function to show users at a glance if the Contact is a smoker using some JavaScript.

The JavaScript will look at these three fields, and if one of the fields indicate that the user is a smoker, they will see the following notification:

[Figure 0] Example of notification working

Figure 1 illustrates the different data types that we will be basing the alert off. I will add these all in the script so that you can pick and choose which data type you will need as they all need to be handled a bit differently.

I've keyed the different data types with their own colours in the image so that you can distinguish them:

  • Orange = Boolean
  • Blue = Whole Number
  • Red = Lookup

[Figure 1] Contact Form containing

Step 1 - Identify your Data Types and adapt the code

Like I previously stated, the JavaScript will handle each Data Type a bit differently, so the first step is to identify which fields you want to base your alerts off and what their Data Types are. After you do this, you can take a look at the code and adapt it to your fields' data types.

Step 1A - Explaining the code

I will now break the code down bit-by-bit, so you can best adapt it to your situation.

  • The first 4 lines creates our function that encapsulates the logic. It then gets the form context so we can access the fields on our form.

[Figure 2] First 4 lines of code explained.

  • The next batch of code stores the values that are currently in the fields on the specific record selected. This will be checked to determine if the Contact is a smoker by storing them in different variables.
  • As a reminder: Orange = Boolean | Blue = Whole Number | Red = Lookup
  • For the Boolean and Whole Number no additional context is needed.
  • For the Lookup, as you can see we've had to define the GUID so that the code understands which item in the related table indicates that the Contact is the smoker.

[Figure 3] Storing the current values of the fields in

  • The code highlighted in Green below creates a variable to determine if the notification should be shown. If any of the conditions are true, this variable will consequently become true and drive the logic to show the notification.

Boolean

  • The code highlighted in Orange determines if the field 'hrashid_smoker' (Boolean) is equal to True (True = Yes and False = No in Power Apps Boolean fields).
  • If you want the notification to show if the Boolean field is No, in the brackets of the if statement replace ('isSmoker' with 'isSmoker = False')

Whole Number

  • The code highlighted in Blue determines if the field 'hrashid_smokedperday' (Whole Number) is more than 0. You can adjust the '> 0' to work with your logic.

Lookup

  • The code highlighted in Red determines if the field 'hrashid_additionaldetails' (Lookup) matches the target GUID stored in the variable 'targetGuid'. It formats the GUID which is in the field and compares it to the one stored in the 'targetGuid'.

Figures 3 & 4 are where you'll be adapting this code the most. You can remove any field types or conditions you do not need, and change the names of the field to match your unique names.
[Figure 4] The

  • The final lines of the script contains an 'if statement' to check if the 'showNotification' variable is true (i.e. Any of the conditions indicate the Contact is smoking). If so, it will show the warning notification. If not, it will clear the notification. This does not need to be modified.

[Figure 5] Final lines of the script.

Step 1B - Copy the code into Visual Studio Code

You can now copy the code below into Visual Studio Code and adapt it as you need. Please ensure you save the file as '.js' to turn it into a JavaScript file.

// Function to check smoking-related conditions and show a notification if any are met
function checkSmoker(executionContext) {
    // Get the form context
    var formContext = executionContext.getFormContext();

    // Retrieve the value of the 'hrashid_smoker' boolean field
    var isSmoker = formContext.getAttribute("hrashid_smoker").getValue();

    // Retrieve the value of the 'hrashid_smokedperday' number field
    var smokedPerDay = formContext.getAttribute("hrashid_smokedperday").getValue();

    // Retrieve the value of the 'hrashid_additionaldetails' lookup field
    var additionalDetails = formContext.getAttribute("hrashid_additionaldetails").getValue();

    // Define the GUID to check against for the 'hrashid_additionaldetails' lookup field
    var targetGuid = "04ca431d-9a37-ef11-a316-002248c824c7";

    // Initialize a variable to determine if the notification should be shown
    var showNotification = false;

    // Check if the 'hrashid_smoker' field is true
    if (isSmoker) {
        showNotification = true;
    }

    // Check if the 'hrashid_smokedperday' field value is greater than 0
    if (smokedPerDay > 0) {
        showNotification = true;
    }

    // Check if the 'hrashid_additionaldetails' lookup field matches the target GUID
    if (additionalDetails && additionalDetails.length > 0) {
        // Get the ID of the lookup field and remove any curly braces
        var lookupId = additionalDetails[0].id.replace(/[{}]/g, '').toLowerCase();
        // Compare the cleaned lookup ID with the target GUID
        if (lookupId === targetGuid) {
            showNotification = true;
        }
    }

    // Show or clear the notification based on the conditions
    if (showNotification) {
        // Show a warning notification if any condition is met
        formContext.ui.setFormNotification("This person is a smoker.", "WARNING", "smokerNotification");
    } else {
        // Clear the notification if none of the conditions are met
        formContext.ui.clearFormNotification("smokerNotification");
    }
}

// To call this function on form load, add an event handler in the form properties
// and set the function name to checkSmoker        

Step 2 - Add the code to your Solution and Form

Next, you need to add the code to your solution, and then the form you want to apply this notification to. If you're unsure how to do this, I've got a tutorial on my website here that you can check out:

Please complete Steps 2 & 3 in the article above and feel free to come back here to move onto Step 3 of this article.

Step 3 - Configure the JS Library in your Form

Once you've got the JS Library in your Environment and Solution, you will need to configure it so it runs 'On Load' and 'On Save' of your form.

You can use the Figure 6 to accompany you which match to the points below:

  1. Select 'Events' in your right navigation.
  2. Select the 'On Save' property.
  3. Select '+ Event Handler'.
  4. Select the Check Smoker [Or your custom name] Library you added in Step 2.
  5. Write 'checkSmoker' in the 'Function' box.
  6. Ensure you tick the 'Pass Execution context as first parameter' box.
  7. Repeat for 'On Load'.

[Figure 6] Please zoom in for reference.

Step 4 - Test Your Code

[Figure 7] Code testing working!

If you got some value out of this, please leave a like, comment, and consider reposting to help someone else out.

Thank you for your time.


To view or add a comment, sign in

More articles by Howdang Rashid

Insights from the community

Others also viewed

Explore topics