Get Current User ID and Name in Javascript MS CRM 2011
11 May 2011 7 Comments
in MS CRM 2011
If you want to get current user id in crm 2011 form you can use Xrm.Page.context, you have to use
getUserId() method for this you can use it like below
Xrm.Page.context.getUserId()
But if you want to get current user name then you can use below function to retrieve it
function Getinfo() {
var context;
var serverUrl;
var UserID;
var ODataPath;
context = Xrm.Page.context;
serverUrl = context.getServerUrl();
UserID = context.getUserId();
ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;
var retrieveUserReq = new XMLHttpRequest();
retrieveUserReq.open(“GET”, ODataPath + “/SystemUserSet(guid’” + UserID + “‘)”, true);
retrieveUserReq.setRequestHeader(“Accept”, “application/json”);
retrieveUserReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8″);
retrieveUserReq.onreadystatechange = function () {
retrieveUserReqCallBack(this);
};
retrieveUserReq.send();
}
function retrieveUserReqCallBack(retrieveUserReq) {
if (retrieveUserReq.readyState == 4 /* complete */) {
if (retrieveUserReq.status == 200) {
var retrievedUser = this.parent.JSON.parse(retrieveUserReq.responseText).d;
if (retrievedUser.FullName!= null)
alert(retrievedUser.FullName);
//To check picklist
if(retrievedUser.AccessMode!=null)
alert(retrievedUser.AccessMode.Value); // for picklist we need to check value
}
else {
alert(“Error in Fetching User data”);
}
}
}
Enjoy !!



Aug 25, 2011 @ 06:23:59
can you tell me how to use these functions?
Aug 25, 2011 @ 08:38:19
you need to create webresource and need to call Getinfo, where you want to get data, for example if you want to get is onchange of some field attached webresource in ms crm form and call Getinfo function on change of particular field.
let me know if you need any other information
Apr 29, 2012 @ 01:48:21
great post, it works well thanks! Any idea on how it can be modified to retrieve other values from picklist (optionset) fields on the SystemUserSet? For example, however can I retrieve the Access Mode value from the picklist that is on the User form?
Apr 30, 2012 @ 05:43:40
Hi Simon,
you just need to use AccessMode field name instead of FullName.
Apr 30, 2012 @ 06:13:41
Thanks Mahender, that was the first thing I tried hoping it would be that easy however it falls back onto the error message. Maybe something to do with the fact AccessMode is a picklist field not just a straight text field?
Apr 30, 2012 @ 11:07:56
yes because this is a picklist you need to write as alert(retrievedUser.AccessMode.Value);
May 02, 2012 @ 05:02:55
Thanks Mahender, very helpful.