How to Set a Lookup Field to Another Lookup Field on a Dynamics 365 Power Apps Form using JavaScript

4 Comments
BEFORE WE START, 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

 

There may be cases where you need to set a lookup field on a Dynamics 365 / Power Apps form, where you want to default the value to another lookup on the form using JavaScript to default the field value.

For example, on the Account form, we have the owner of the account (field OwnerId), and we have a custom field called My System User Field (new_mysystemuserfield) which is a system user lookup which looks like below:

Let’s say we want to set the System User field to the Owner Id field on load of the form, and perhaps add some additional business logic if we wanted to (your use case may be more complex):

Create a new web resource on the account form on load with the following code:

function OnLoad(context) {
   console.log("On Load");
   
   // First get the OwnerId lookup
   var OwnerId = FormContext.getAttribute("ownerid").getValue();
   var Id = OwnerId[0].id;
   var Name = OwnerId[0].name;
   var EntityType = OwnerId[0].entityType;
   
   // Create new lookup array
   
   var lookup = [];
    lookup[0] = {};
    lookup[0].id = Id;
    lookup[0].entityType = EntityType;
    lookup[0].name = Name;

   // Get and Set New Lookup
    var MySystemUserField = FormContext.getAttribute("new_mysystemuserfield");
    MySystemUserField.setValue(lookup);   
}

Now when opening the form, this field is defaulted from our Owner field:

 

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

 

4 Responses to How to Set a Lookup Field to Another Lookup Field on a Dynamics 365 Power Apps Form using JavaScript

  1. Hi Carl! Thank you so much for this. As always, these posts are big help for the community.

    I’ve noticed a little change in the framework (I think). After initialization, you must create an object and it will work like a charm.

    lookup[0] = new Object();

    • Hi Arafat! That is interesting. It seems to be working for me still, but wondering if it’s version specific. I’ll keep an eye out for this, thanks so much for adding this detail. – Carl

  2. Hi Carl!!
    Amazing one here!!
    Is it possible to get other field properties of a lookup using javascript web resource??

Leave a Reply

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