3

How do you get a User object from Person or Group field value using JSOM/JavaScript API? I am looking for something like this (See Vadim Gremyachev answer), but let me be clear I DO NOT WANT the current logged in user as in that code example:

user = clientContext.get_web().get_currentUser();

I want a User object that is populated by a person or group field from a list column! The overall goal is to have a user object so I can do things like:

alert('The Display Name of the user is ' + user.get_loginName());
alert('The Account Name of the user is ' + user.get_id());
alert('The email address of the user is ' + user.get_email());
alert('The User Title is ' + user.get_title());
etc.

Also note in my scenario I am only using single user people picker fields so no complicated arrays or user collections needed when getting the value from the people picker field.

My current environment is:
SharePoint 2013 Enterprise On-premise
5

You can use a code like this:

Below example uses JSOM

SP.SOD.executeFunc("sp.js", "SP.ClientContext", function(){
        SP.SOD.registerSod("sp.userprofiles.js", SP.Utilities.Utility.getLayoutsPageUrl("sp.userprofiles.js"));
        SP.SOD.executeFunc("sp.userprofiles.js", "SP.UserProfiles.PeopleManager", getTaskListItem);
});
        function getTaskListItem(){
        var item;    
            var clientContext = new SP.ClientContext.get_current();

            var web = clientContext.get_web();

            var list = web.get_lists().getByTitle('Tasks'); //replace with your custom list

            item = list.getItemById(1);

            clientContext.load(item);

            clientContext.executeQueryAsync(onSuccess, onFailure);
        }
        function onSuccess(){
        var context = SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var userName = item.get_item("AssignedTo").get_lookupValue();//replace AssignedTo with your person column
        var user = web.ensureUser(userName);
        var email = user.get_email();
    var loginName = user.get_loginName();

        }
        function onFailure(){

            console.log('Failure!');
        }

If you are planning to use REST api, the call would be as below:

https://siteurl/_api/web/lists/getbytitle('Tasks')/items/?$select=ID,Title,Body,Issue/Id,TaskDueDate,Created,AssignedTo/FirstName,AssignedTo/LastName,AssignedTo/Name,AssignedTo/Id,AssignedTo/Email&$expand=Issue/Id,AssignedTo/Id

It can also be used as follows:

here AssignedTo is a person/group column, but you can add you custom person column as well.

var getTasks = function () {
    var promise = $.ajax({
        url: "/_api/web/lists/getbytitle('Tasks')/items/?" + 
            "$select=ID,Title,Body,Issue/Id,TaskDueDate,Created,AssignedTo/FirstName,AssignedTo/LastName,AssignedTo/Name,AssignedTo/Id,AssignedTo/Email&" +
            "$expand=Issue/Id,AssignedTo/Id",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
    });
    return promise;
};
  • Trying to use the JSOM code above and keep getting the below error; amI missing a script reference (see below.) – Shane Gib. Oct 24 '16 at 15:09
  • The property or field 'Email' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. – Shane Gib. Oct 24 '16 at 15:10
  • Here are the script references in the web part page: – Shane Gib. Oct 24 '16 at 15:11
  • <SharePoint:ScriptLink name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false"/> <SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false"/> <SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false"/> <SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false"/> <SharePoint:ScriptLink name="sp.RequestExecutor.js" runat="server" LoadAfterUI="true" Localizable="false"/> – Shane Gib. Oct 24 '16 at 15:13
  • 1
    Uncaught Error: The property or field 'LoginName' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. – codemirror Jul 4 '17 at 12:33
3

When you access a User field from a list item using the JavaScript Object Model, the value is treated as if it were a lookup field. You can only really invoke fieldValue.get_lookupValue() to get the user's display name and fieldValue.get_lookupId() to get the ID of the user's entry in the site collection user info list.

To get the actual SPUser object, so that you can drill down into the email and login name, you can use the SPWeb.ensureUser() method.

 var clientContext = new SP.ClientContext();
 var list = clientContext.get_web().get_lists().getByTitle("Example Code").getItemById(1);
 clientContext.load(item);
 clientContext.executeQueryAsync(
      function(){ // successfully retrieved value from list item
           var author = item.get_item("Author");
           var user = clientContext.get_web().ensureUser(author.get_lookupValue());
           clientContext.load(user);
           clientContext.executeQueryAsync(
                function(){ // successfully ensured user from user name
                     var email = user.get_email();
                     var login = user.get_loginName();
                     var displayName = user.get_title();
                     alert("User LoginName: " + login + "\nUser Email: " + email + "\nUser Display Name: " + displayName);
                },function(sender,args){ // on error
                     alert(args.get_message());
                }
           );
      },
      function(sender,args){ // on error
           alert(args.get_message());
      }
 );
0

In this case I would use REST APIs to get the People/Group (Name with presence) column's username by expanding the column e.g. ....$expand=user/group

and then there is an ensureUser Method in the JS Client Object Model:

http://msdn.microsoft.com/en-us/library/ff408786.aspx

Which you could use to create User object.

0

Did you get any answer for this? Please refer if the below post helps you:

http://gocodin.blogspot.in/2017/04/how-to-get-lookup-valueusername-from.html

  • 1
    Link-only answers are discouraged, as links can break. Should've summarized the method to look for the user object in the Person field that they used, ex: var _User = listItem.get_item(colValuesEnum.Author)[0].get_lookupValue(); or if multiple users: if (listItem.get_item(colValuesEnum.Author).length > 1) { .... } loop through each of them: for (var i = 0; i < listItem.get_item(colValuesEnum.Author).length; i++) { _User = listItem.get_item(colValuesEnum.Author)[i].get_lookupValue(); } but use var user = web.ensureUser(_User); var email = user.get_email(); on each _User. – vapcguy Mar 8 at 22:57
  • 1
    If you add that detail to your answer, I'll delete my comment & vote it up. – vapcguy Mar 8 at 23:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.