Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Use of Web API in form scripts

Posted on by 2,665

Hi,

I am trying to refactor my script in order to use web api. We are about to upgrade to CRM 2016. This particular script has worked fine until now.

But in CRM 2016, it is failing to work and upon some research I found it might be due to use of old odata endpoints in the script. So I tried to use the new web api url in the script but it still fails.

I did debug the script and found my userRequest.status gives me 0 for some reason. I've also used plural name of the entity in query.

Can some one please guide me in the right direction? Thanks for any help.

All this script does is, takes user id and retrieves an attribute(country) from the systemuser entity filtered on the user id.

function getUserCountry(userId) {
debugger;
var createdOn=Xrm.Page.getAttribute("createdon").getValue();
                if(createdOn!=null)
                {
           return; 
                }

	    var serverUrl = Xrm.Page.context.getClientUrl();
	    //var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc"; 
            var ODataPath = serverUrl + "/api/data/v8.0";  
	    var userRequest = new XMLHttpRequest(); 
	    userRequest.open("GET", ODataPath + "/SystemUsersSet(guid'" + userId + "')?$select=new_country", true); 
		userRequest.setRequestHeader("OData-MaxVersion", "4.0");
		userRequest.setRequestHeader("OData-Version", "4.0");
	    userRequest.setRequestHeader("Accept", "application/json"); 
	    userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8"); 
	    userRequest.send();
	    if (userRequest.status === 200) {
	    var retrievedUser = JSON.parse(userRequest.responseText).d; 
            var country = retrievedUser.new_country; // new_country is the lookup field name inside user entity
return country;
}
	    else {
	        return "error";
	    }
	}

		
		var owner = Xrm.Page.getAttribute("ownerid").getValue();
		if(owner!=null) {
		var ownerId = owner[0].id;
		var country = getUserCountry(ownerId);

if(country!=null)
		{
		var countryValue = new Array();
		countryValue[0] = new Object();
		countryValue[0].id = country.Id;
		countryValue[0].name = country.Name;
		countryValue[0].entityType = country.LogicalName;

		Xrm.Page.getAttribute("new_country").setValue(countryValue);
}

		


*This post is locked for comments

  • Verified answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Use of Web API in form scripts

    Hi,

     I believe you need to add

     userRequest.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");

     msdn.microsoft.com/.../gg334767.aspx

  • Verified answer
    a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Use of Web API in form scripts

    Hello,

    Try to include following to your request:

    userRequest.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

    That should enable return of Lookup Names along with ids.

  • crmprogrammer2013 Profile Picture
    crmprogrammer2013 2,665 on at
    RE: Use of Web API in form scripts

    Thanks guys,

    I worked out some of the mistakes I made with your suggestions. I think I am almost there except with one more thing.

    How do I access the lookup value instead of its id?

    Currently I am using

     var country=retrievedUser["_new_country_value"]

    to access country name from the retrieved results. But this gives me guid instead of country name.

    I did found that formattedvalue should be used in order to get the lookup value. So I tried like below but I am getting 'undefined' country variable.

    var country=retrievedUser["_new_country_value@OData.Community.Display.V1.FormattedValue"];

    Am I thinking correct ?

    Thanks again.

  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Use of Web API in form scripts

    Didn't fully read Alex's answer, but I guess he covered it.

  • Suggested answer
    Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Use of Web API in form scripts

    Your Request is not correct:

    1. You do use SystemUsersSet anymore, but just use SystemUsers

    2. To get the record for a particular Guid, your just pass the value in parenthesis, no need for guid text in it)

    Example:

    crmdomain.api.crm.dynamics.com/.../systemusers(8c61da4f-8778-e345-8d96-1cc1de79838e)

    Hope this helps.

  • ashlega Profile Picture
    ashlega 34,475 on at
    RE: Use of Web API in form scripts

    Hi,

     there are some differences - not sure what else can be wrong in the script (see Andrew's answer for a more thorough approach), but, at the very least, don't use "Set" and 'guid'.. you'll find some examples here:

    msdn.microsoft.com/.../gg334767.aspx

    For instance:

    api/data/v8.2/incidents(39dd0b31-ed8b-e511-80d2-00155d2a68d4)

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Use of Web API in form scripts

    Hello,

    To make your refactoring easier try to use CRMRest Builder to build your query and get initial version of code - github.com/.../releases

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!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans