Showing posts with label Set Lookup Field value from the related entity using web API Call. Show all posts
Showing posts with label Set Lookup Field value from the related entity using web API Call. Show all posts

Sunday, May 17, 2020

Set lookup field value in Dynamics 365 v9.x


How to set lookup field value on the custom entity from the related entity field value


Dynamics 365 Web API Call

1. Function to Set custom entity Currency lookup field value from opportunity entity using Dynamics 365 web API call. Read and set Currency lookup value from the opportunity entity.

Replace the attribute name with your required attribute names.

//Function to set lookup

function setNameCurrencyId(executionContext) {
    var formContext = executionContext.getFormContext();
    if (formContext.getAttribute("new_opportunityid").getValue() != null) {
 
        var opportunityId = formContext.getAttribute("new_opportunityid").getValue()[0].id;
 
        Xrm.WebApi.retrieveMultipleRecords("opportunity", "?$select=opportunityid,name,_transactioncurrencyid_value&$filter=opportunityid eq '" + opportunityId + "'").then(
            function success(result) {
                var opportunityName = result.entities[0]["name"];
                formContext.getAttribute("new_name").setValue(opportunityName);
                for (var i = 0; i < result.entities.length; i++) {
                    var p = result.entities[0];
                    if (p != null) {
                        var lookup = new Array();
                        lookup[0] = new Object();
                        lookup[0].id = p["_transactioncurrencyid_value"];
                        lookup[0].name = p["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                        lookup[0].entityType = p["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                        formContext.getAttribute("transactioncurrencyid").setValue(lookup);
                    }
                    break;
                }
            },
            function (error) {
                console.log("Error in 'setNameCurrencyId' function. Message: " + error.message);
                alert("Error: " + error.message);
            }
        );
    }
}

---------------------------------------------------------------------------------
That's All...
Thank You... Happy Learning ...

More Useful Links:
Reusable JavaScripts Codes  Simple Plugin Development  Develop a Console App