web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Answered

How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

(0) ShareShare
ReportReport
Posted on by 1,589

I need to get the Guid of a record whose name value I specify via JavaScript. 

I am using the code below, but am getting an error. 

function MyFn(executionContext) {
    var recordname = "Sample Record Name";
    var formContext = executionContext.getFormContext();
    var globalContext = Xrm.Utility.getGlobalContext();

    //Retrieve Franchise Default Type GUID whose Name Equals "Sample Record Name" using WEB API
    //Step-1 : create fetch xml in adv find and replace all double quotes with single quote inside properties to shape it as a string
    var fetchXml = ''  
        ''  
        ''  
        ''  
        ''  
        ''  
        ' '  
        ''  
        ''  
        '';
    //Step-2 : encode URI : var encodedFetchXML = encodeURI(fetchxml)
    var encodedFetchXML = encodeURI(fetchXml);

    //Step-3 : create a query path with query and odata partial url : var query = "/api/data/v9.2/entityname?fetchXml=" encodedFetchXML ;
    var query = "/api/data/v9.2/cpp_franchiseedefaulttype?fetchXml="   encodedFetchXML;

    //Step-4 : create complete path : var path = globalContext.getClientUrl()   query ;
    var finalpathwithquery = globalContext.getClientUrl()   query;


    //Step-5 : create a XmlHttpRequest to retrieve data
    var data = null;
    var isAsync = false;

    var req = null;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
    }

    req.open("GET", finalpathwithquery, isAsync);
    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);
                data = result;
            }
            else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();

    //Step-6 show return result values
    var returnedrecord = null;
    for (var i = 0; i < data.value.length; i  ) {
        returnedrecord = returnedrecord   " | "   data.value[i].id;
    }
    alert(returnedrecord);
}

The specific error I am getting is:

One of the scripts for this record has caused an error.
For more details, download the log file.
data is nullSession
Id: b6ed80ca-878b-4c99-9994-e79eab0a9fe7
Correlation Id: 2e3d6fe9-cf6e-4ff9-8289-4ec5cec1a746
Event Name: onload
Function Name: OnLoad
Web Resource Name: cpp_/entities/franchisedefault/franchisedefaultV9.js
Solution Name: Active
Publisher Name: DefaultPublisher
Time: Mon May 03 2021 18:08:27 GMT-0400 (Eastern Daylight Time)

If I pull the log file, there is not anything of relevance in there as shown below. 

OnLoad@redacted.url/.../franchisedefaultV9.js:80:25
_executeFunctionInternal@redacted.url/.../app.js
execute@redacted.url/.../app.js
_executeIndividualEvent/<@redacted.url/.../app.js
i@redacted.url/.../app.js
_executeIndividualEvent@redacted.url/.../app.js
_executeEventHandler@redacted.url/.../app.js
execute@redacted.url/.../app.js
_executeSyncAction@redacted.url/.../app.js
_executeSync@redacted.url/.../app.js
executeAction@redacted.url/.../app.js
A/</</</t.dispatch@redacted.url/.../app.js
boot/a</e</</r.dispatch</<@redacted.url/.../app.js
dispatch@redacted.url/.../app.js
dispatch@redacted.url/.../app.js
_t@redacted.url/.../11.js
execute/</</</</</</<@redacted.url/.../33.js


Error Details:
Event Name: onload
Function Name: OnLoad
Web Resource Name: cpp_/entities/franchisedefault/franchisedefaultV9.js
Solution Name: Active
Publisher Name: DefaultPublisher
Where am I going wrong specifically?
I have the same question (0)
  • Verified answer
    Community Member Profile Picture
    on at

    Hi Jim,

    Why not using record name as filter directly?

    You can try to use CRM REST Builder to create XmlHttpRequest to retrieve data, which can make build request more easily:

    Download page: https://github.com/jlattimer/CRMRESTBuilder

    For example, I want to get one account named ‘A. Datum Corporation (sample)’ .

    1.Import zip file to the solution (Go Settings > Solutions), then open the tool.

     pastedimage1620095428331v5.png

    2.Set it as following screenshot:

     pastedimage1620095300626v1.png

    3.Click ‘create request’ button to get code, then run it.

    pastedimage1620095344493v3.png

    4.Result:

    pastedimage1620095569958v1.png

    Regards,

    Leah Ju

    Please mark as verified if the answer is helpful. Welcome to join hot discussions in Dynamics 365 Forums.

  • ACECORP Profile Picture
    1,589 on at

     Will the JavaScript code generated this way also execute within the D365 Mobile App?

  • Suggested answer
    meelamri Profile Picture
    13,216 User Group Leader on at

    Why do you want to use XMLHTTP? I will use the xrm.webapi for this scenario.

  • vishal bagadia_crm Profile Picture
    490 on at

    t

  • vishal bagadia_crm Profile Picture
    490 on at

    t

  • Verified answer
    vishal bagadia_crm Profile Picture
    490 on at

    Hi Jim,

    Please refer the given modified code. I have copied your code and modified it accordingly

    function MyFn(executionContext) {
        var recordname = "Sample Record Name";
        var formContext = executionContext.getFormContext();
        var globalContext = Xrm.Utility.getGlobalContext();
        var finalpathwithquery = Xrm.Page.context.getClientUrl()   "/api/data/v9.1/cpp_franchiseedefaulttype?$select=cpp_franchiseedefaulttypeid,cpp_name&$filter=name eq 'Sample Record Name'";
    
    
        //Step-5 : create a XmlHttpRequest to retrieve data
        var data = null;
        var isAsync = false;
    
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
    
    	req.open("GET",finalpathwithquery,isAsync);
    	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 results = JSON.parse(this.response);
    				data = results;
    			} else {
    				Xrm.Utility.alertDialog(this.statusText);
    			}
    		}
    	};
    	req.send();
    	
        //Step-6 show return result values
        var returnedrecord = null;
        for (var i = 0; i < data.value.length; i  ) {
            returnedrecord = returnedrecord   " | "   data.value[i].id;
        }
        alert(returnedrecord);
    }


    Please mark this answer, if it solves your purpose.

    Thanks In Advance.
    CRM Developer

  • Community Member Profile Picture
    on at

    You can try to test it, it should work.

  • ACECORP Profile Picture
    1,589 on at

    Thank you to everyone for the recommendations and assistance!

    I ended up using WebApi as shown below and that works great. 

    function TheMagicFunction(executionContext, MyVariable, ExtraqParam) {
    /*STUFF HERE*/
        var a = 1;
        if (client == "Web") {
            if (/*STUFF HERE == THE STUFF*/ a == a) {
                if (/*MORE STUFF HERE == MORE STUFF*/ a == a) {
                    Xrm.WebApi.online.retrieveMultipleRecords("myentity", "?$select=myid&$filter=fieldname eq 'valuethatineed'").then(
                        function success(results) {
                            for (var i = 0; i < results.entities.length; i  ) {
                                M/*ore Stuff Here*/
                                // Open the form
                                Xrm.Navigation.openForm(entityFormOptions, parameters).then(
                                    function (success) {
                                        console.log(success);
                                    },
                                    function (error) {
                                        console.log(error);
                                    });
                            }
                        },
                        function (error) {
                            Xrm.Utility.alertDialog(error.message);
                        });
                }
    
            }
        }
        else if (client == "Mobile"); {
            if (/*STUFF HERE == THE STUFF*/ a == a) {
                if (/*MORE STUFF HERE == MORE STUFF*/ a== a) {
                    Xrm.WebApi.online.retrieveMultipleRecords("myentity", "?$select=myid&$filter=fieldname eq 'valuethatineed'").then(
                        function success(results) {
                            for (var i = 0; i < results.entities.length; i  ) {
                                //More Stuff Here
                                // Open the form
                                Xrm.Navigation.openForm(entityFormOptions, parameters).then(
                                    function (success) {
                                        console.log(success);
                                    },
                                    function (error) {
                                        console.log(error);
                                    });
                            }
                        },
                        function (error) {
                            Xrm.Utility.alertDialog(error.message);
                        });
                }
    
            }
        }
    }

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 80

#3
Martin Dráb Profile Picture

Martin Dráb 64 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans