Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Forums / Sales forum / Using FetchXML to get ...
Sales forum

Using FetchXML to get Lookup fields

(0) ShareShare
ReportReport
Posted on by 160

This fetch query below will retrieve an Opportunity record but when I try to get the ID and Name of the parentaccountid lookup field, which I know has a value, all that gets returned is 'undefined'.  Is this a syntax problem or are we unable to get lookup fields from FetchXML?

function SetAccount() {

try {

var OppId;

var OppName;

var OppType;

 //get the OpportunityId from the Quote that is loading

if (Xrm.Page.getAttribute("opportunityid").getValue() != null) {

OppId = Xrm.Page.getAttribute("opportunityid").getValue()[0].id;

OppName = Xrm.Page.getAttribute("opportunityid").getValue()[0].name;

OppType = Xrm.Page.getAttribute("opportunityid").getValue()[0].entityType;

}

console.log("**************** OppId=" + OppId + " OppName=" + OppName + " OppType=" + OppType);

var FetchXML = "<?xml version='1.0'?>" +

"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0' >" +

"<entity name='opportunity' >" +

"<attribute name='name' />" +

"<attribute name='parentaccountid' />" +

"<attribute name='parentcontactid' />" +

"<order attribute='parentaccountid' descending='true' />" +

 "<filter type='and'>" +

"<condition attribute='opportunityid' value='" + OppId + "' uitype='opportunity' uiname='" + OppName + "' operator='eq'/>" +

"</filter>" +

"</entity >" +

"</fetch >"

 

var encodedFetchXML = encodeURI(FetchXML);

var queryPath = "/api/data/v8.0/opportunities?fetchXml=" + encodedFetchXML;

var requestPath = Xrm.Page.context.getClientUrl() + queryPath;

var req = new XMLHttpRequest();

req.open("GET", requestPath, true);

req.setRequestHeader("Accept", "application/json");

req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

req.onreadystatechange = function () {

if (this.readyState === 4) {

this.onreadystatechange = null;

if (this.status === 200) {

var returned = JSON.parse(this.responseText);

var results = returned.value;

var accountName = "";

for (var i = 0; i < results.length; i++) {

accountName = results[i]["name"]; //This return the name

console.log("---name = " + accountName);

var tacct = results[i]["parentaccountid"]; //RETURNS UNDEFINED, when I know a value is there

console.log("---tacct = " + tacct);

if (tacct != null) {

var acctguid = tacct[0].id;

var acctname = tacct[0].name;

Xrm.Page.getAttribute("falcon_account").setValue([{ id: acctguid, name: acctname, entityType: "account" }]);

}

Xrm.Page.getAttribute("falcon_quotenote1").setValue("name = " + accountName);

}

}

};

req.send();

} catch (err) {

console.log("************* ERROR **************" + err.message);

}

console.log("%%%%%% DONE WITH SCRIPT %%%%%%%%%%");

}

Categories:
  • Michel van den Brink Profile Picture
    4,697 on at
    RE: Using FetchXML to get Lookup fields

    Any time, here to help :-)

    I added an additional code sample to my last post, just for good measure

  • FalconTwo52 Profile Picture
    160 on at
    RE: Using FetchXML to get Lookup fields

    Thanks Michel, you have been very helpful!

  • Verified answer
    Michel van den Brink Profile Picture
    4,697 on at
    RE: Using FetchXML to get Lookup fields

    Hello,

    The field '_parentaccountid_value' only contains the GUID itself, not an object with ID and Name, like a regular entity reference.

    This is the default setting for the WebApi, for lookups it always just returns the GUID.

    If you want the name of the record as well, you'll have to include an extra header:

    req.setRequestHeader('Prefer', 'odata.include-annotations="*"');


    In the returned JSON object, the name of your record will now be returned as this field:

    '_parentcustomerid_value@OData.Community.Display.V1.FormattedValue'

      

    Take a look at this article on how to deal with lookups in the WebApi, especially section 'Retrieve data about lookup properties':

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/query-data-web-api#retrieve-data-about-lookup-properties

      

    With some small adjustments here and there, your original code example would turn out like this:

    function SetAccount() {
    
        var OppId;
        var OppName;
        var OppType;
    
        //get the OpportunityId from the Quote that is loading
        if (Xrm.Page.getAttribute("opportunityid").getValue() != null) {
            OppId = Xrm.Page.getAttribute("opportunityid").getValue()[0].id;
            OppName = Xrm.Page.getAttribute("opportunityid").getValue()[0].name;
            OppType = Xrm.Page.getAttribute("opportunityid").getValue()[0].entityType;
        }
        console.log("**************** OppId=" + OppId + " OppName=" + OppName + " OppType=" + OppType);
    
        var queryPath = '/api/data/v8.0/opportunities(' + OppId + ')?$select=name,_parentaccountid_value,_parentcontactid_value';
        var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
    
        var req = new XMLHttpRequest();
        req.open("GET", requestPath, true);
        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) {
                this.onreadystatechange = null;
                if (this.status === 200) {
                    var returned = JSON.parse(this.responseText);
                    var results = returned.value;
                    var accountName = "";
                    for (var i = 0; i < results.length; i++) {
                        var acctguid = results[i]["_parentaccountid_value"]; // Only the GUID
                        var acctname = results[i]["_parentcustomerid_value@OData.Community.Display.V1.FormattedValue"] // the name of the record
                        console.log("---acctguid = " + acctguid);
                        console.log("---acctname = " + acctname);
                        if (acctguid != null) {
                            Xrm.Page.getAttribute("falcon_account").setValue([{ id: acctguid, name: acctname, entityType: "account" }]);
                        }
                    }
                }
            };
        };
        req.send();
    
        console.log("%%%%%% DONE WITH SCRIPT %%%%%%%%%%");
    }


  • FalconTwo52 Profile Picture
    160 on at
    RE: Using FetchXML to get Lookup fields

    Thanks for the reply!  So I changed the code and now I do get a GUID in the variable tacct , But if I try to get the ID and Name from tacct I get undefined?

                           accountName = accountName + results[i]["name"];

                           console.log("---name = " + accountName);

                           var tacct = results[i]["_parentaccountid_value"];

                           console.log("---tacct = " + tacct);

                           //var tacct = results[i]["parentaccountid"].id;

                           if (tacct != null) {

                               var acctguid = tacct[0].id;

                               var acctname = tacct[0].name;

                               console.log("---acctguid = " + acctguid + " acctname=" + acctname);

                               Xrm.Page.getAttribute("falcon_account").setValue([{ id: acctguid, name: acctname, entityType: "account" }]);

                           }

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at
    RE: Using FetchXML to get Lookup fields

    Hello,

    When using the WebApi, lookup fields are returned with an altered field name in the JSON response.

    The pattern they follow is: _fieldname_value.

    For parentaccountid, that would mean the field name is called '_parentaccountid_value' in the JSON response

      

    Take a look at this article about retrieving data with lookups, especially the section named "Lookup properties":

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/web-api-types-operations#bkmk_lookupProperties 

      

    Sidenote: Your query can be simplified with the WebApi to only this GET request, you are not restricted to using FetchXml, you can use this simple OData query:

    var queryPath = '/api/data/v8.0/opportunities(' + OppId + ')?$select=name,_parentaccountid_value,_parentcontactid_value';

    For more on how to query your data with OData, please take a look at this article:

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/query-data-web-api 

      

    Hope this helps you. If you have any other questions, please let me know!

    If you found my answer helpful, please help the community by marking it as verified :-)

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

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,095 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 232,866 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans