I have found this useful post that helped me to achieve my goal:
http://mahenderpal.wordpress.com/2011/05/11/get-current-user-id-and-name-in-javascript-ms-crm-2011/
I have then generalized the function in order to allow the retrieving of different user fields.
The function below accepts an array with the fields names we want to retrieve.
/*
Retrieve current user info.
fields is an array containing fields schema name to retrieve: if null --> all record fields will be retrieved
*/
function GetUserInfo(fields) {
var context;
var serverUrl;
var UserID;
var ODataPath;
var oDataQuery;
var retrievedUserInfo;
context = Xrm.Page.context;
serverUrl = context.getServerUrl();
UserID = context.getUserId();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var retrieveUserReq = new XMLHttpRequest();
oDataQuery = ODataPath + "/SystemUserSet(guid'" + UserID + "')";
if (fields) {
oDataQuery = oDataQuery + "?$select=";
for (var i = 0; i < fields.length; i++) {
oDataQuery = oDataQuery + fields[i] + ",";
}
oDataQuery = oDataQuery.substring(0, oDataQuery.length - 1); //Remove the last ","
}
retrieveUserReq.open("GET", oDataQuery, false);
retrieveUserReq.setRequestHeader("Accept", "application/json");
retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveUserReq.onreadystatechange = function () {
if (retrieveUserReq.readyState == 4 /* complete */) {
if (retrieveUserReq.status == 200) {
retrievedUserInfo = JSON.parse(retrieveUserReq.responseText).d;
}else {
//Handle errors
}
}
};
retrieveUserReq.send(); return retrievedUserInfo;
}
Hope it can be useful.
Happy coding.
Rate this posting:
{[['']]}
No comments:
Post a Comment