Skip to main content

Notifications

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,579

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?
  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    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);
                        });
                }
    
            }
        }
    }

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    You can try to test it, it should work.

  • Verified answer
    vishal bagadia_crm Profile Picture
    vishal bagadia_crm 490 on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    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

  • vishal bagadia_crm Profile Picture
    vishal bagadia_crm 490 on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    t

  • vishal bagadia_crm Profile Picture
    vishal bagadia_crm 490 on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    t

  • Suggested answer
    meelamri Profile Picture
    meelamri 13,204 User Group Leader on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

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

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

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

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: How to get GUID of a Record using JavaScript WebApi FetchXML via Entity Name and Record Name?

    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.

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

News and Announcements

Announcing Category Subscriptions!

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 Verified Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,370 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans