Populate user lookup from JavaScript

Populating lookup filed is little different than the normal attributes population in MSD 365. Here is the example of system user population with JavaScript.

Here are some related functions to get User’s (logged in user/ current user) information …

getUserId >> Xrm.Page.context.getUserId() is responsible to get the GUID of the SystemUser.Id value for the current user.

getUserName >> Xrm.Page.context.getUserName() is responsible to get a text string of the username / the current user.
getUserRoles >> Xrm.Page.context.getUserRoles() returns an array of strings that represent the GUID values of each of the security roles that the user is associated with or any teams that the user is associated with.

Setting User lookups

The common reason for retrieving the username and the user id is because both values are needed if you want to programmatically set a lookup field in CRM.

Example code is shown below

For MSD-365 V9, as many things are deprecated

function PopulateCurrentUser(executionContext) {
    //populate current user 
    var setUservalue = new Array();
    setUservalue[0] = new Object();

    var userSettings = Xrm.Utility.getGlobalContext().userSettings; // userSettings is an object with user information.

    setUservalue[0].entityType = 'systemuser';
    setUservalue[0].id = userSettings.userId; // The user's unique id
    setUservalue[0].name = userSettings.userName; // The user's name

    executionContext.getFormContext().getAttribute("soft_activeuser").setValue(setUservalue);
}

For earlier versions

//populate current user 
var setUservalue = new Array();
setUservalue[0] = new Object();
setUservalue[0].id = Xrm.Page.context.getUserId();
setUservalue[0].entityType = 'systemuser';
setUservalue[0].name = Xrm.Page.context.getUserName();

Xrm.Page.getAttribute("soft_lookupfieldName").setValue(setUservalue);
For more information explore on MSDN page – Client-side context (client-side reference)
That’s all.
Thanks.