Here's my code, some of which I got online, so I don't fully understand it all, but I know what it's doing, pretty much.
// Check if it's a create form var CREATE_FORM = 1; var userName1; var formType= Xrm.Page.ui.getFormType(); if (formType == 1) { // Set 'Completed by' field to record owner //Get GUID of logged user var user = Xrm.Page.context.getUserId(); var userId = user.substring(1,37); // Read the CRM Context to determine the CRM URL var serverUrl = Xrm.Page.context.getServerUrl() var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc"; var ODATA_EntityCollection = "/SystemUserSet"; // Specify the ODATA Query var ODATA_Query = "(guid\'" + userId + "')"; // Combine into the final URL var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query; //Calls the REST endpoint to retrieve data $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", datatype: "json", url: ODATA_Final_url, beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); }, success: function (data, textStatus, XmlHttpRequest) { userName = data.d.FullName; userName1 = userName ; //alert("userName1 set to: " + userName1); }, error: function (XmlHttpRequest, textStatus, errorThrown) { alert('Error: '+ ODATA_Final_url); } }); var lookup = new Array(); lookup[0] = new Object(); lookup[0].id = userId ; //alert("userName1 value now: " + userName1); lookup[0].name = userName1 ; lookup[0].entityType = "systemuser"; Xrm.Page.getAttribute("vs_completedby").setValue(lookup); } }
When I leave the commented out alert boxes in, it runs fine - username1 has a value, and the lookup displays this username correctly. However, when I comment out the alert lines, username1 is undefined. Do I need some sort of wait interval to allow the Rest services to complete the data retrieval?? And the alert box is causing a slight delay, so that's why username1 gets populated when they aren't commented out??? I can't have the alert boxes in my code though!
Thanks.