April 16, 2013

Get current user's full name with a synchronous call

An AJAX request can be made also synchronous, this can be useful when we want to make a simple and fast request inside CRM 2011.
In this example we will retrieve the full name of the current user and set the value to a custom field called "new_userfullname".
function getCurrentUserFullName() {
    var serverUrl;
    if (Xrm.Page.context.getClientUrl !== undefined) {
        serverUrl = Xrm.Page.context.getClientUrl();
    } else {
        serverUrl = Xrm.Page.context.getServerUrl();
    }
    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc"; 
    var userRequest = new XMLHttpRequest(); 
    userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false); 
    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 userFullName = retrievedUser.FullName;
        return userFullName;
    }
    else {
        return "error";
    }
}
 
var fullName = getCurrentUserFullName();
Xrm.Page.getAttribute("new_userfullname").setValue(fullName);

0 comments:

Post a Comment