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

4 Answers 4

4

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;
};
13
  • Trying to use the JSOM code above and keep getting the below error; amI missing a script reference (see below.)
    – Shane Gib.
    Oct 24, 2016 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, 2016 at 15:10
  • Here are the script references in the web part page:
    – Shane Gib.
    Oct 24, 2016 at 15:11
  • 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, 2017 at 12:33
  • 1
    clientContext and item are out of scope Oct 12, 2021 at 11:50
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());
      }
 );
3
  • You shouldn't need get_title() for the Display Name - only to use .get_lookupValue() directly off of the item.get_item('Author') call.
    – vapcguy
    Mar 30 at 17:10
  • 1
    @vapcguy Good point, although I believe that the value returned by get_lookupValue can be configured from the column settings, so it's not always guaranteed to be the display name
    – Thriggle
    Apr 12 at 20:42
  • That would be true if it were a column on a list, and isn't a bad point, but the "Author" field is a built in field. It represents the "Created By" value.
    – vapcguy
    Apr 22 at 20:47
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

2
  • 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, 2019 at 22:57
  • 1
    If you add that detail to your answer, I'll delete my comment & vote it up.
    – vapcguy
    Mar 8, 2019 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.