Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

Retrieving value of lookup entity using CRM REST

Posted on by 5

Hi guys, I am new to CRM Dynamics . I have a requirement.

Lets assume that I have 2 related Entities : "Cat" and "Dog" and I have simple fields "Cat_Food" and  "Dog_Food" on them respectively . I have a lookup field of Entity Dog on Entity Cat's Form named as "Lookup_Cat". Now as soon as a lookup value of Dog is selected , I want Cat's "Cat_Food" field to be populated with the (selected lookup)Dog's "Dog_Food" field's value using Javascript.

Now I have seen on many websites that CRM REST BUILDER was suggested. I had Used it but It is not populating and neither giving any error: Here's the code:

// JavaScript source code

function abc(executionContext)
{
var formContext = executionContext.getFormContext();
var new_dogfood;
var lookup = new Array();
lookup = formContext.getAttribute("Cat_Food").getValue();
if (lookup != null)
{
var name = lookup[0].name;
var id = lookup[0].id;
var entityType = lookup[0].entityType;
}
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/Dog(id)?$select=Dog_Food", false);
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.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
new_dogfood = result["Dog_Food"];
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();

formContext.getAttribute("Cat_Food").setValue(new_dogfood);
}

Any help would be appreciated.

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Retrieving value of lookup entity using CRM REST

    Hi partner,

    If you are using V9.X, you could also use "Xrm.WebApi" method to get value more easier.

    Here is the sample for you.

    function getValueFromLookUp(executionContext){
        var formContext=executionContext.getFormContext();
        //get lookup field
        var Lookup_Cat=formContext.getAttribute("Lookup_Cat");
        if(Lookup_Cat!=null){
            //get lookup field record id
            var value=Lookup_Cat.getValue();
            var id=value[0].id;
            //use record id to retrieve other field value
            Xrm.WebApi.retrieveRecord("Dog",id,"?$select=Dog_Food").then(
                function success(result){
                    //get the dog_food value and set it to cat_food field
                    var dog_food=result.Dog_Food;
                    formContext.getAttribute("Cat_Food").setValue(dog_food);
                },
                function (error){
                    console.log(error.message);
                }
            )

        }
        
    }

    https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrieverecord

    Best Regards,

    Leo

  • Suggested answer
    Alex Fun Wei Jie Profile Picture
    Alex Fun Wei Jie 33,626 on at
    RE: Retrieving value of lookup entity using CRM REST

    Hi,

    Since you are using CRM online. Now there is a new way to retrieve the data. You can refer below blogs for examples.

    carldesouza.com/.../

  • Suggested answer
    Sanket87 Profile Picture
    Sanket87 160 on at
    RE: Retrieving value of lookup entity using CRM REST

    You need to slice the curly braces of the id and then pass it to the fetch .

    Here is an example of that.

    function RetrieveSourceEmailFromFax()
    {
    try {
    var _zh_sourceemail_value;
    var emailID = Xrm.Page.data.entity.getId().slice(1, -1); // slice likr this
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/faxes(" + emailID + ")?$select=_zh_sourceemail_value", false);
    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);
    _zh_sourceemail_value = result["_zh_sourceemail_value"];
    var _zh_sourceemail_value_formatted = result["_zh_sourceemail_value@OData.Community.Display.V1.FormattedValue"];
    var _zh_sourceemail_value_lookuplogicalname = result["_zh_sourceemail_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }
    }
    };
    req.send();
    return _zh_sourceemail_value;
    }
    catch (e) {

    }


    }

    Try it out and try to debug your 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,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans