CRM 2011 – Setting a user lookup with the logged in user with Javascript

Sometimes you need to log the current user in a User Lookup.

Xrm.Page.context.getUserId()

if you wanted to set a user lookup field you would need to do this


var setUservalue = new Array();
 setUservalue[0] = new Object();
 setUservalue[0].id = Xrm.Page.context.getUserId();
 setUservalue[0].entityType = 'systemuser';
//setUservalue[0].name = retrievedUser.FullName;

Xrm.Page.getAttribute("meta_aurarrangedby").setValue(setUservalue)

meta_aurarrangedby is a user lookup field

This will set the correct guid but the user name will be blank until the page is reloaded if you want to add the user name then you need to retrieve the user name using the guid the example code below will do this using an OData query but you will have to add the json2.js file to the entity so it can be called from your javascript.

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)

var setUservalue = new Array();
 setUservalue[0] = new Object();
 setUservalue[0].id = Xrm.Page.context.getUserId();
 setUservalue[0].entityType = 'systemuser';
 setUservalue[0].name = retrievedUser.FullName;

Xrm.Page.getAttribute("meta_aurarrangedby").setValue(setUservalue)
 }

else {

 }
 }
}

The Xrm.Page.context has quite a few useful functions the functions are listed on this page

The getServerUrl is very useful as is the getUserRoles

Xrm.Page.context provides access to the following functions:

  • getAuthenticationHeader: A deprecated method that returns the encoded SOAP header necessary to use Microsoft Dynamics CRM Web service calls using JScript.
  • getCurrentTheme Returns a string representing the current Microsoft Office Outlook theme chosen by the user.
  • getOrgLcid: Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the base language for the organization.
  • getOrgUniqueName: Returns the unique text value of the organizations name.
  • getQueryStringParameters: Returns an array of key value pairs representing the query string arguments that were passed to the page.
  • getServerUrl: Returns the base server URL. When a user is working offline with Microsoft Dynamics CRM for Microsoft Office Outlook, the URL is to the local Microsoft Dynamics CRM Web services.
  • getUserId: Returns the GUID value of the SystemUser.id value for the current user.
  • getUserLcid: Returns the LCID value that represents the Microsoft Dynamics CRM Language Pack that is the user selected as their preferred language.
  • getUserRoles: Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
  • isOutlookClient: Returns a Boolean value indicating if the user is using Microsoft Dynamics CRM for Microsoft Office Outlook.
  • isOutlookOnline: Returns a Boolean value indicating whether the user is connected to the Microsoft Dynamics CRM server while using Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access. When this function returns false, the user is working offline without a connection to the server. They are interacting with an instance of Microsoft Dynamics CRM running on their local computer.
  • prependOrgName: Prepends the organization name to the specified path.
Advertisements

14 thoughts on “CRM 2011 – Setting a user lookup with the logged in user with Javascript

  1. Simon April 30, 2012 / 2:20 am

    Very helpful post, thanks. How can I adapt it so that I can re-use the code elsewhere on other forms? For example, I’d like to set the value to specific fields (like you have with “meta_aurarrangedby”) as a seperate function – not within this one. I am guessing I have to call the ‘Getinfo’ function within my seperate function but I am not sure how to best do this?

    Like

  2. Tauqir Hussain November 20, 2012 / 11:43 am

    i am getting this error, i try to call your Getinfo() methid on load.

    There was an error with this field’s

    customized event.

    Field:window Event:onload

    Error:Access is denied.

    Like

    • Hosk November 20, 2012 / 11:44 am

      I would recommend you press F12 and step through the javascript with the debugger to see if you can work out what is going on

      Like

      • Tauqir Hussain November 20, 2012 / 12:52 pm

        i got the error after this line
        UserID = context.getUserId();
        i checked the UserID in alert and it works. but the following line shows an error message.
        ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;

        Like

      • Hosk November 20, 2012 / 1:04 pm

        Are you using CRM on premise or online, I think that it might only work with on premise.

        you should check the value of the serverUrl and then check the url of ODataPath in the browser to make sure it’s putting in a valid value

        Like

  3. Nick Hollis January 8, 2013 / 6:10 pm

    RE: Tauqir (I know it’s late but may help someone else), you may get that error if you are using Localhost to browse to your CRM deployment. context.getServerUrl will give you the full server name and the browser will not like that. It will think your are cross site scripting and hence the access denied.

    Like

    • Yousuf July 3, 2013 / 11:49 am

      Thanks Hosk for the Post and thanks Nick for your reply. It help’s me alot.

      Like

  4. basesCop January 6, 2014 / 9:41 pm

    Продаём базы почтовых ящиков с правительственных сайтов
    zakupki.gov.ru и bus.gov.ru. Общее количество – 30219 шт.
    Базы верифицированы, очищены от дублей.
    Идеально подходят для почтовой рассылки коммерческих предложений,
    бизнес-проектов и т.д.
    Дата сбора – 3 января 2014 г.
    ICQ – 658548888.

    Like

  5. Padmini Tiwari November 23, 2016 / 7:17 am

    hey ben,

    Im getting error “failed to load resource , server responded with error 404” on the send line retrieveUserReq.send();

    Like

  6. Padmini Tiwari November 23, 2016 / 7:20 am

    Hey Ben,

    Im getting Failed to load resource , server responded with 404 not found error on the retrieveUserReq.send(); line

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s