Skip to main content

Notifications

Announcements

No record found.

Dynamics 365 general forum

JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

Posted on by Microsoft Employee

HI all,

I'm having an issue with the following code, and hope one of you can point out what i have wrong. The code runs and i see my first alert but don't get the second.

function setCaseCompany() {

    //Get the Resource lookup off of the record
    var resource = Xrm.Page.getAttribute('msdyn_bookableresourceid').getValue();

    //if contact exist, attempt to pull back the contact record
    if (resource != null) {

        var resourceId = resource[0].id;
        var serverUrl;

        if (Xrm.Page.context.getClientUrl !== undefined) {
            serverUrl = Xrm.Page.context.getClientUrl();
        }
        else {
            serverUrl = Xrm.Page.context.getServerUrl();
        }

        alert("here");

        var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
        var rollRequest = new XMLHttpRequest();

        rollRequest.open("GET", ODataPath + "/BookableResourceSet(guid'" + resourceId + "')", false);
        rollRequest.setRequestHeader("Accept", "application/json");
        rollRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        rollRequest.send();

        //If request was successful, parse the associated record name

        if (rollRequest.status == 200) {

            alert("Here");

            var retrievedRoll = JSON.parse(rollRequest.responseText).d;

            alert(retrievedRoll.rev_defaultroleId);

            if (retrievedRoll != null && retrievedRoll.new_defaultrole != null) {

                alert('NOT HERE!');

                //set the value of the field to the field “new_defaultrole”
                var lookup = new Object();
                var lookupValue = new Array();
                lookup.id = retrievedRoll.new_defaultrole.Id;
                lookup.entityType = "bookableresourcecategory";
                lookup.name = retrievedRoll.new_defaultrole.Name;
                lookupValue[0] = lookup;
                Xrm.Page.getAttribute("msdyn_resourcecategory").setValue(lookupValue);
                Xrm.Page.getControl("msdyn_resourcecategory").clearNotification();
            }
            else {
            }

        }
        else {
        }

    }
    else {
    }
}

Error message:

Error: parameter is not passed or parameter is nNull or undefined at Function.Error.create 

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Still need help on this sorry, how do i put my CRM Rest query into a JavaScript to return the field value default role?

    It runs when i add a new team member (teammembersignup) and select the resource on a new record, it should then populate the role field.

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/msdyn_projectteammembersignups(AE55156F-0D32-E811-A972-000D3A1A7A9)?$expand=msdyn_BookableResource($select=rev_defaultrole)", 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 msdyn_projectteammembersignupid = result["msdyn_projectteammembersignupid"];
                if (result.hasOwnProperty("msdyn_BookableResource")) {
                    var msdyn_BookableResource_rev_defaultrole = result["msdyn_BookableResource"]["rev_defaultrole"];
                }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();


  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Graeme,

    I would still recommend to use WEB API instead of OrganizationData endpoints as these are now deprecated and will be removed in future. If you still want to use 2011 endpoints, you can use the below code. I have tested this against my trial and is working fine. You can change the columns as per your needs. This code was built using CRM Rest Builder tool so I don't have to worry about what schema name should I use and it took me literally less than 2 minutes :)

    ==============

    var req = new XMLHttpRequest();

    req.open("GET", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/BookableResourceSet(guid'B6B2B8D5-D956-E711-812E-70106FA12A71')?$select=AccountId,msdyn_GenericType,Name", 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 result = JSON.parse(this.responseText).d;

               var accountId = result.AccountId;

               var msdyn_GenericType = result.msdyn_GenericType;

               var name = result.Name;

           } else {

               Xrm.Utility.alertDialog(this.statusText);

           }

       }

    };

    req.send();

    ==============

    URL: instance.crm6.dynamics.com/.../BookableResourceSet(guid'B6B2B8D5-D956-E711-812E-70106FA12A71')?$select=AccountId

    Hope this helps.

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Graeme,

    Here is sample code using web API , you can easily create REST API using CRMRestBuilder instead of old way to retrieve the data.

    You can have a look below article and also download the CRMRestBuilder from here -https://github.com/jlattimer/CRMRESTBuilder

    https://goutamdascrm.wordpress.com/2018/05/05/why-dynamics-365-web-api/

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/bookableresources(1204E0A4-66A1-E811-A97E-000D3A1ADA5F)?$select=_accountid_value,bookableresourceid,name,resourcetype", 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 _accountid_value = result["_accountid_value"];
                var _accountid_value_formatted = result["_accountid_value@OData.Community.Display.V1.FormattedValue"];
                var _accountid_value_lookuplogicalname = result["_accountid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                var bookableresourceid = result["bookableresourceid"];
                var name = result["name"];
                var resourcetype = result["resourcetype"];
                var resourcetype_formatted = result["resourcetype@OData.Community.Display.V1.FormattedValue"];
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();


    Hope this helps.

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Try with schema name   BookableResourceId and also make sure new_defaultrole field name also should be schema name. You can find the schema name from settings --> Customization--> Customize the System --> Expand Entity --> Fields .

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    The URl is:

    crminstancename.crm.dynamics.com/.../BookableResourceSet$select=new_defaultrole&$filter=bookableresourceid%20eq%20guid'{A255156F-0D32-E811-A972-000D3A1A7A9B}'

    when i goto it in a browser session is get:

    No property 'bookableresourceid' exists in type 'Microsoft.Xrm.Sdk.Entity' at position 0.

    Also, msdyn_bookableresourceid also doesn't work.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Goutam, unfortunately, I'm getting the following:

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Graeme,

    Try with this -

           function setCaseCompany() {
                //Get the Resource lookup off of the record
                var resource = Xrm.Page.getAttribute('msdyn_bookableresourceid').getValue();
                //if contact exist, attempt to pull back the contact record
                if (resource != null) {
                    var resourceId = resource[0].id;
                    var serverUrl;
                    if (Xrm.Page.context.getClientUrl !== undefined) {
                        serverUrl = Xrm.Page.context.getClientUrl();
                    }
                    else {
                        serverUrl = Xrm.Page.context.getServerUrl();
                    }
                   
                    var ODATA_ENDPOINT = "/xrmservices/2011/OrganizationData.svc/";
                    var selectQuery = "BookableResourceSet?$select=columnname1,columnname2,columnname3&$filter=msdyn_bookableresourceId eq guid'" + resourceId + "'"; // replace columnname  , make sure id should be logical name so please add the correct name )               
    
                    $.support.cors = true;
                    $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        async: false,
                        datatype: "json",
                        url: serverUrl + ODATA_ENDPOINT  + selectQuery,
                        beforeSend: function (XMLHttpRequest) {                      
                            XMLHttpRequest.setRequestHeader("Accept", "application/json");
                        },
                        success: function (data, textStatus, XmlHttpRequest) {
                            if (data != null && data.d != null && data.d.results != null && data.d.results.length > 0) {
                                for (var i = 0; i < data.d.results.length; i++) {
                                    if (data.d.results[i] != null) {                                    
                                        // Set your lookup here , you will get the entity column value writing - data.d.results[i].columnname1  ,  data.d.results[i].columnname2 ..... 
                                        
                                    }
                                } 
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            alert("An error occurred while retrieving Roles")
                        }
                    });
                }
                else {
                }
            }


  • RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Graeme,

    It would be must faster to use the tool and generate the script. If you already have some code which is working fine then you can compare. You can share the working code here to get the suggestions why this is not working.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    It is online, however i have used a similar odata request on another page and that works fine. I just can't get this working. I will look at the rest builder but just want this workign in the meantime.

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: JavaScript OData Request to get Role from Resource Lookup on a Project Team Member Record

    Hi Graeme,

    If I am not wrong, the crm version id Dynamics 365 Online. If yes then you shouldn't be using Odata and instead use Web API to retrieve the details.  

    I would suggested to doenload and use CRM Rest Builder to build the WEB API request. This is the easiest way to build the query as well as execute it and see the results.

    www.toplinestrategies.com/.../crm-rest-builder-useful-tool-working-crm-2016’s-web-api

    You can download the tool here- github.com/.../releases

    You can also refer this blog similar to the requirement you have- community.dynamics.com/.../how-to-get-value-from-a-look-or-other-related-entity-using-calculated-field-in-microsoft-dynamics-crm

    Hope this helps.

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... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans