Adding an OnChange Script Programmatically in Dynamics 365 Power Apps

1 Comment

In this post, we will look at how to programmatically add an OnChange script in Dynamics 365 Power Apps, so when a user tabs off a field, the script is run.

First, when we tab off a field, such as this fax field on the account record, we would like our script to run:

Without doing this programmatically, we would select the field and select Change Properties:

Then go to Events and select the OnChange event and add a new script:

Easy enough. But let’s do it programmatically instead. We will use addOnChange:

formContext.getAttribute(arg).addOnChange(myFunction)

The code. Let’s register 3 functions to run. We can see that we can easily do this:

function RunOnLoad(executionContext) {
    var formContext = executionContext.getFormContext();
    formContext.getAttribute("fax").addOnChange(HelloWorld);
    formContext.getAttribute("fax").addOnChange(HelloWorld2);
    formContext.getAttribute("fax").addOnChange(HelloWorld3);
}

function HelloWorld(executionContext) {
   console.log("Hello World");   
}

function HelloWorld2(executionContext) {
   console.log("Hello World 2");   
}

function HelloWorld3(executionContext) {
   console.log("Hello World 3");   
}

Let’s register this on OnLoad of the form and pass the executionContext as the first parameter:

Go into Dev Tools on the browser, and we see all 3 change scripts have run:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

One Response to Adding an OnChange Script Programmatically in Dynamics 365 Power Apps

  1. What happens if you call addOnChange multiple times for the same function? For example:

    fld.addOnChange(function () { ShowHideSection(formContext) }); // gets called 4 times

    Will it call ShowHideSection() 4 times per change event?

Leave a Reply

Your email address will not be published. Required fields are marked *