Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Answered

Javascript to retrieve values from different entities and set the value to a case

Posted on by 2,095

Hi all,

This is my scenario:

On cases I've got the following field:

Customer - One of the out of the box fields that can point to either Account or Contact. I've added a javascript function so that it filters only to contacts and doesn't display any accounts. Therefore Customers will now always be a contact

Account - A custom lookup field referencing the Account entity. This needs to default to the Company Name account ID of the contact that was set in the Customer field above. I created a javascript function as per the below and it worked quite well.

function setAccount(executionContext) {
    var formContext = executionContext.getFormContext();
    var customer = formContext.getAttribute("customerid").getValue();
    // Check if customer field contains data
    if (customer != null){
        // convert the returned Id into a useable format
        var newid = customer[0].id.slice(1, -1);
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts(" newid ")?$select=_parentcustomerid_value", true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.onreadystatechange = function() {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(this.response);
                    var companyNameId = result["_parentcustomerid_value"];
                    var companyNameFormattedValue = result["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
                    var companyNameEntityName = result["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                    formContext.getAttribute("new_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName }]);
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
    }
}

Currency - A custom lookup field referencing the Currency entity. I now need this to get the currency ID of the companyNameId variable in the above javascript and then set it to the custom Currency lookup field on cases. This is where I'm getting stuck. No matter what I do I can't seem to set the currency ID to the same value as from the account. Below is the addition to the above code I've added to do this. Not sure what I'm doing wrong. Any help would be greatly appreciated.

function setAccountAndCurrency(executionContext) {
    var formContext = executionContext.getFormContext();
    var customer = formContext.getAttribute("customerid").getValue();
    // Check if customer field contains data
    if (customer != null){
        // convert the returned Id into a useable format
        var newid = customer[0].id.slice(1, -1);
        // Get contact details with Company Name ID
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts(" newid ")?$select=_parentcustomerid_value,new_filterValue", true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.onreadystatechange = function() {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(this.response);
                    //Store company ID into a format usable in cases
                    var companyNameId = result["_parentcustomerid_value"];
                    var companyNameFormattedValue = result["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
                    var companyNameEntityName = result["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                    // Retrieve the filter value from contact for use later on
                    var filterId = result["new_filterValue"];
                        if(companyNameId != null){ //Check to see if contacts has an associated company
                        // Set the refrential Account lookup field value on cases to the company of the contact
                        formContext.getAttribute("new_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName }]);
                        var req = new XMLHttpRequest();
                        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts(" companyNameId ")?$select=_transactioncurrencyid_value", true);
                        req.setRequestHeader("OData-MaxVersion", "4.0");
                        req.setRequestHeader("OData-Version", "4.0");
                        req.setRequestHeader("Accept", "application/json");
                        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                        req.onreadystatechange = function() {
                            if (this.readyState === 4) {
                                req.onreadystatechange = null;
                                if (this.status === 200) {
                                var result = JSON.parse(this.response);
                                var currencyId = result["_transactioncurrencyid_value"];
                                var currencyFormattedValue = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                                var currencyEntityName = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                                if(currencyId != null){
                                    formContext.getAttribute("new_currency").setValue([{name: currencyFormattedValue, id: currencyId, entityType: currencyEntityName}]);
                                }

                    };
                    req.send();
                    }
                        }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
}
    }}

I've never tried to retrieve values from multiple entities to then set lookup field values on a case before.

  • Verified answer
    Naveen Ganeshe Profile Picture
    Naveen Ganeshe 3,393 User Group Leader on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Hey Mike,

    Good to know that it is working now. I forgot to pass the formContext to other function.

    Please mark the answer as verified if it was helpful for you.

    Thanks

  • Suggested answer
    Pawar Pravin  Profile Picture
    Pawar Pravin 5,227 on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Could you please try once by calling rest service in synchronous mode:

    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/contacts("+newid+")?$select=_parentcustomerid_value,new_filterValue", false);

  • Suggested answer
    MikeC282 Profile Picture
    MikeC282 2,095 on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Hi Naveen,

    I tried the above code and it doesn't seem to be calling the other function for SetCurrencyLookup at all. I then tried moving:

    "formContext.getAttribute("new_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName });"

    to the original function. Below is the code I used:

    function setAccount(executionContext) {
        var formContext = executionContext.getFormContext();
        var customer = formContext.getAttribute("customerid").getValue();
        // Check if customer field contains data
        if (customer != null){
            // convert the returned Id into a useable format
            var newid = customer[0].id.slice(1, -1);
            var req = new XMLHttpRequest();
            req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts(" newid ")?$select=_parentcustomerid_value,new_filterValue", true);
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
            req.onreadystatechange = function() {
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var result = JSON.parse(this.response);
                        var companyNameId = result["_parentcustomerid_value"];
                        var companyNameFormattedValue = result["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
                        var companyNameEntityName = result["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                        // save this for future use
                        var filterValue = result["new_filterValue"];
                        if (companyNameId !=null){ // Check if company exists for contact
                            formContext.getAttribute("newn_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName }]);
                            // Trying to call the second function
                            setCurrencyLookup (companyNameId);
                        }
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
        }
    }
    
    function setCurrencyLookup(companyNameId)
    {
                        var req = new XMLHttpRequest();
                        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts(" companyNameId ")?$select=_transactioncurrencyid_value", true);
                        req.setRequestHeader("OData-MaxVersion", "4.0");
                        req.setRequestHeader("OData-Version", "4.0");
                        req.setRequestHeader("Accept", "application/json");
                        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                        req.onreadystatechange = function() {
                            if (this.readyState === 4) {
                                req.onreadystatechange = null;
                                if (this.status === 200) {
                                var result = JSON.parse(this.response);
                                var currencyId = result["_transactioncurrencyid_value"];
                                var currencyFormattedValue = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                                var currencyEntityName = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                                if(currencyId != null){
                                    formContext.getAttribute("new_countrycurrency").setValue([{name: currencyFormattedValue, id: currencyId, entityType: currencyEntityName}]);
                                }
    
                    };
                }
            };
         req.send();
    }

    Pre_2D00_fill.png

    I know that each of the functions works as CRM REST builder was able to retrieve the currency values from accounts but I can't get the first function to call the second.

    Transaction-ID-called.png

    EDIT: So I found what the issue was. I realised I didn't pass the formContext to the second function meaning that when it tried to set the currency lookup field it couldn't. The below code will work.

    function setAccount(executionContext) {
        var formContext = executionContext.getFormContext();
        var customer = formContext.getAttribute("customerid").getValue();
        // Check if customer field contains data
        if (customer != null){
            // convert the returned Id into a useable format
            var newid = customer[0].id.slice(1, -1);
            var req = new XMLHttpRequest();
            req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts(" newid ")?$select=_parentcustomerid_value,new_filterValue", true);
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
            req.onreadystatechange = function() {
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var result = JSON.parse(this.response);
                        var companyNameId = result["_parentcustomerid_value"];
                        var companyNameFormattedValue = result["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
                        var companyNameEntityName = result["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                        // save this for future use
                        var filterValue = result["new_filterValue"];
                        if (companyNameId !=null){ // Check if company exists for contact
                            formContext.getAttribute("newn_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName }]);
                            // Trying to call the second function
                            setCurrencyLookup (formContext,companyNameId);
                        }
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
        }
    }
    
    function setCurrencyLookup(formContext,companyNameId)
    {
                        var req = new XMLHttpRequest();
                        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts(" companyNameId ")?$select=_transactioncurrencyid_value", true);
                        req.setRequestHeader("OData-MaxVersion", "4.0");
                        req.setRequestHeader("OData-Version", "4.0");
                        req.setRequestHeader("Accept", "application/json");
                        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                        req.onreadystatechange = function() {
                            if (this.readyState === 4) {
                                req.onreadystatechange = null;
                                if (this.status === 200) {
                                var result = JSON.parse(this.response);
                                var currencyId = result["_transactioncurrencyid_value"];
                                var currencyFormattedValue = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                                var currencyEntityName = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                                if(currencyId != null){
                                    formContext.getAttribute("new_countrycurrency").setValue([{name: currencyFormattedValue, id: currencyId, entityType: currencyEntityName}]);
                                }
    
                    };
                }
            };
         req.send();
    }

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Hi Mike ,

    Below code is working for me , you can get help from here - 

    function setCurrencyLookupValue(executionContext) {   
        var formContext = executionContext.getFormContext();
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts(475b158c-541c-e511-80d3-3863bb347ba8)?$select=_transactioncurrencyid_value", true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(this.response);
                    var _transactioncurrencyid_value = result["_transactioncurrencyid_value"];
                    var _transactioncurrencyid_value_formatted = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                    var _transactioncurrencyid_value_lookuplogicalname = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
    
                    if (_transactioncurrencyid_value != null) {                 
                        var lookupValue = new Array();
                        lookupValue[0] = new Object();
                        lookupValue[0].id = _transactioncurrencyid_value; // GUID of the lookup id
                        lookupValue[0].name = _transactioncurrencyid_value_formatted; // Name of the lookup
                        lookupValue[0].entityType = "transactioncurrency"; //Entity Type of the lookup entity
                        formContext.getAttribute("new_currency").setValue(lookupValue); // You need to replace the lookup field Name..
                    }
    
    
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }
    

  • Suggested answer
    Naveen Ganeshe Profile Picture
    Naveen Ganeshe 3,393 User Group Leader on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Hello Mike,

    Please try to put your currency retrieve logic in a different function and call that function inside the main one. I think your function is not working because of the same object name for XMLHttpRequest for both retrievals. Please see below code after correction

    function setAccountAndCurrency(executionContext) {
        var formContext = executionContext.getFormContext();
        var customer = formContext.getAttribute("customerid").getValue();
        // Check if customer field contains data
        if (customer != null){
            // convert the returned Id into a useable format
            var newid = customer[0].id.slice(1, -1);
            // Get contact details with Company Name ID
            var req = new XMLHttpRequest();
            req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts(" newid ")?$select=_parentcustomerid_value,new_filterValue", true);
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
            req.onreadystatechange = function() {
                if (this.readyState === 4) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var result = JSON.parse(this.response);
                        //Store company ID into a format usable in cases
                        var companyNameId = result["_parentcustomerid_value"];
                        var companyNameFormattedValue = result["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"];
                        var companyNameEntityName = result["_parentcustomerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                        // Retrieve the filter value from contact for use later on
                        var filterId = result["new_filterValue"];
                            if(companyNameId != null){ //Check to see if contacts has an associated company
                                  SetCurrencyLookup(companyNameId);
                        }
                            }
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            };
            req.send();
        };
    }
        
        function SetCurrencyLookup(companNameId)
        {
                            formContext.getAttribute("new_account").setValue([{ name: companyNameFormattedValue, id: companyNameId, entityType: companyNameEntityName }]);
                            var req = new XMLHttpRequest();
                            req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts(" companyNameId ")?$select=_transactioncurrencyid_value", true);
                            req.setRequestHeader("OData-MaxVersion", "4.0");
                            req.setRequestHeader("OData-Version", "4.0");
                            req.setRequestHeader("Accept", "application/json");
                            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                            req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                            req.onreadystatechange = function() {
                                if (this.readyState === 4) {
                                    req.onreadystatechange = null;
                                    if (this.status === 200) {
                                    var result = JSON.parse(this.response);
                                    var currencyId = result["_transactioncurrencyid_value"];
                                    var currencyFormattedValue = result["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"];
                                    var currencyEntityName = result["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                                    if(currencyId != null){
                                        formContext.getAttribute("new_currency").setValue([{name: currencyFormattedValue, id: currencyId, entityType: currencyEntityName}]);
                                    }
    
                        };
                    }
                };
             req.send();
        }

  • ajyendra Profile Picture
    ajyendra 1,730 on at
    RE: Javascript to retrieve values from different entities and set the value to a case

    Can u show us what error you got from this code?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans