locked
Trying to set lookup value via Javascript RRS feed

  • Question

  • 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.

    Tuesday, August 20, 2013 12:40 PM

Answers

  • Hi,

    Because the OData call is asynchronous, the code that sets the value of the lookup needs to be moved into the success function:

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

    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); }, error: function (XmlHttpRequest, textStatus, errorThrown) { alert('Error: '+ ODATA_Final_url); } }); } }

    The reason the alerts are making the code seems as if it "works" is because the alert function halts code execution until the user clicks ok, which is giving the asynchronous OData call time to complete. Without the alert, the OData call has not completed by the time the code that sets the lookup executes - hence the null username. Moving the code into the callback function guarantees that it only runs when the OData call has completed.

    • Proposed as answer by MJFPalmer Tuesday, August 20, 2013 1:23 PM
    • Marked as answer by crmNewbie1978 Tuesday, August 20, 2013 1:28 PM
    Tuesday, August 20, 2013 12:48 PM
  • Hi,
    your jQuery function is asynchronous, this means that userName will be filled only when "success" function is called, but your code to fill the lookup is executed just after you ask the value (happens that the value is not ready yet).

    You have 3 solutions:

    1) put the fill of the lookup after the line "userName1 = userName;" inside the success function
    2) change the code to use a synchronous call, you can find an example here http://www.crmanswers.net/2013/04/get-current-users-full-name-with.html
    3) because you are filling this lookup inside a create, if your entity is owner based (means it has ownerid field, it's not an organization based) you can just copy the lookup from the ownerid field:

    if (Xrm.Page.ui.getFormType() == 1)
    {
       var owner = Xrm.Page.getAttribute("ownerid").getValue();
       Xrm.Page.getAttribute("vs_completedby").setValue(owner);
    }



    My blog: www.crmanswers.net



    Tuesday, August 20, 2013 12:53 PM

All replies

  • Hi,

    Because the OData call is asynchronous, the code that sets the value of the lookup needs to be moved into the success function:

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

    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); }, error: function (XmlHttpRequest, textStatus, errorThrown) { alert('Error: '+ ODATA_Final_url); } }); } }

    The reason the alerts are making the code seems as if it "works" is because the alert function halts code execution until the user clicks ok, which is giving the asynchronous OData call time to complete. Without the alert, the OData call has not completed by the time the code that sets the lookup executes - hence the null username. Moving the code into the callback function guarantees that it only runs when the OData call has completed.

    • Proposed as answer by MJFPalmer Tuesday, August 20, 2013 1:23 PM
    • Marked as answer by crmNewbie1978 Tuesday, August 20, 2013 1:28 PM
    Tuesday, August 20, 2013 12:48 PM
  • Hi,
    your jQuery function is asynchronous, this means that userName will be filled only when "success" function is called, but your code to fill the lookup is executed just after you ask the value (happens that the value is not ready yet).

    You have 3 solutions:

    1) put the fill of the lookup after the line "userName1 = userName;" inside the success function
    2) change the code to use a synchronous call, you can find an example here http://www.crmanswers.net/2013/04/get-current-users-full-name-with.html
    3) because you are filling this lookup inside a create, if your entity is owner based (means it has ownerid field, it's not an organization based) you can just copy the lookup from the ownerid field:

    if (Xrm.Page.ui.getFormType() == 1)
    {
       var owner = Xrm.Page.getAttribute("ownerid").getValue();
       Xrm.Page.getAttribute("vs_completedby").setValue(owner);
    }



    My blog: www.crmanswers.net



    Tuesday, August 20, 2013 12:53 PM
  • Thank you both for your replies. I used the second option, and it worked perfectly for me!
    Tuesday, August 20, 2013 1:28 PM