How to Set a Lookup Field Value in Dynamics 365 using JavaScript
Requirement:
- If a CUSTOMER type of field's value is an account, needs to populate another field ("dfa_primarycontactid") with this account's primary contact info.
- If a CUSTOMER type of field's value is a contact, needs to clear the value of another field ("dfa_primarycontactid")
JavaScript:
PopulatePrimaryContact: function (executionContext)
{
var formContext = executionContext.getFormContext();
debugger;
var attributeCustomer = formContext.getAttribute("customerid");
if(attributeCustomer == null || attributeCustomer == undefined)
{
return;
}
//Lookup is an array. Need to get first object.
var customerType = customer.getValue()[0].entityType;
if (customerType == "account")
{
Xrm.WebApi.retrieveRecord("account", customer.getValue()[0].id.replace("{","").replace("}",""), "?$select=_primarycontactid_value").then
(
function success(result)
{
debugger;
primaryContactId = result._primarycontactid_value;
//if Primary Contact is null, set agent primary contact field to null.
if(primaryContactId == null)
{
formContext.getAttribute("dfa_primarycontactid").setValue(null);
}
//if Primary Contact is not vacant, retrieve agent primary contact info, then set agent primary contact field.
else
{
Xrm.WebApi.retrieveRecord("contact", primaryContactId, "?$select=fullname").then
(
function success(result)
{
debugger;
var object = new Array();
object[0] = new Object();
object[0].id = primaryContactId;
object[0].name = result.fullname;
object[0].entityType = "contact"
formContext.getAttribute("dfa_primarycontactid").setValue(object);
},
function (error)
{
//console.log(error.message);/
}
);
}
},
function (error)
{
//console.log(error.message);/
}
)
}
else if (customerType = "contact")
{
formContext.getAttribute("dfa_primarycontactid").setValue(null);
}
else
{
//Show Error Message
}
}
No comments:
Post a Comment