Where you might use this functionality
This functionality is useful because you might need to update a User lookup field to a particular user in situations like
- The current user changed a key field
- The current user is primary contact for a project, account, deliverable.
- Set a text field of the users name for reporting purposes.
Why are you mentioning it
To do retrieve the current user name in CRM 2011 it took a soap call to retrieve the user name field using the Xrm.Page.context.getUserId(). Below is a blog post I wrote
There is now a much easier way to do this in CRM 2013 and CRM 2015. I found this way whilst reading this forum post
Start with the CRM SDK
The Hosk CRM developer mantra is to always start with the CRM SDK to see what methods and functionality exists which can help.
Searching the CRM SDK first helps you see what functionality Microsoft have added, most CRM developers will be surprised the number of new methods added.
It’s very easy for developers to copy and paste existing code in projects but just because it works it doesn’t mean its the best code to use.
This is classic case, the CRM 2011 code is long and involves a soap call, the new functionality added in CRM 2013 allows you to access the data with one line.
Microsoft Client code page – Client-side context (client-side reference)
There are three useful functions about the existing user (there’s another about language but I’m not including it).
- Returns the GUID of the SystemUser.Id value for the current user.
- Returns the name of the current user.
- 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.
This would get you the SystemUser.Id
This would return a text string of the user name
Setting User lookups
The common reason for retrieving the user name and the user id is because both values are needed if you want to programatically set a lookup field in CRM.
Example code is shown below
var setUservalue = new Array(); setUservalue = new Object(); setUservalue.id = Xrm.Page.context.getUserId(); setUservalue.entityType = 'systemuser'; setUservalue.name = Xrm.Page.context.getUserName(); Xrm.Page.getAttribute("LookupField").setValue(setUservalue)
What I have learnt
- Use the CRM SDK to see what functionality exists, there might be a better way
- Microsoft added a new getUserName method in CRM 2013
- You need the guid, name and entity type to set the value of a lookup field
- If you don’t need to set the lookup instantly you can use workflows or plugins
- CRM forum posts provide extremely useful information from a number of CRM developers