HOW TO GET AND SET LOOKUP FIELD VALUES USING JAVASCRIPT IN DYNAMICS 365?

There may be cases where you need to set one lookup field value into another lookup field on the form using JavaScript in Dynamics 365 .

What is Lookup field?
A Lookup field type represents the relationship attribute on the related entity.

Required Attributes of lookup fields:

id: The GUID of the item. Required for set.
name: The name of the item to be displayed. Required for set.
entityType: The entity name of the item. Required for set.

SCENARIO:
On the Case form, we have two fields one is Owner (ownerid) of the Case and another one is Custom field called Developer of the Case (adyt_developerofthecase). We need to set Owner Lookup value to the Developer of the Case Lookup on the Case form using JavaScript.

JavaScript Code:
Getting Owner Lookup of the Case.

function getLookupDetails(executionContext)
{
// Getting Form Context
var formContext = executionContext.getFormContext();
// Getting the value of Case Owner id
var OwnerId = formContext.getAttribute(“ownerid”).getValue();
// Getting the GUID of the lookup record
var Id = OwnerId[0].id;
// Getting Name of the lookup record
var Name = OwnerId[0].name;
// Getting Entity Name of the lookup which entity, the lookup record is belonging to.
// Getting Entity Name of the lookup which entity, the lookup record is belonging to.

var EntityType = OwnerId[0].entityType;

Setting Owner lookup of the Case to Developer of the Case
var lookup = [];   // Creating a new lookup Array

lookup[0] = {};    // new Object
lookup[0].id = Id;  // GUID of the lookup id
lookup[0].name = Name; // Name of the lookup
lookup[0].entityType = EntityType; // Entity Type of the lookup entity
// Getting Developer of the Case and Setting Owner of the case to Developer of the Case
var OwnerId = formContext.getAttribute(“adyt_developerofthecase “).setValue(lookup);
}

Output:
Developer of the Case should be the Owner of the Case.

Lookup Field

Leave a Reply