0

Just wanting to know how to update a user field, like CreatedBy or Author based on a users name e.g. steven.martin? I seem to have it working fine, from a user id, but not from a user name.

get user fields by id

var context = new SP.ClientContext();
var user = context.get_web().getUserById(30); // e.g. user id = 30
context.load(user);
context.executeQueryAsync( 
  function () {
    console.log(user.get_email());
    var userField = user.get_id() + ";#" + user.get_loginName();
    updateUser(userField);
   },
   function (sender, args) {
     console.log('Error retrieving user properties');
   }
);

update user/ author field

function updateUser(userField) {
  var clientContext = new SP.ClientContext("/");
  var list = clientContext.get_web().get_lists().getByTitle("Announcments");
  var listItem = {};
  listItem = list.addItem(new SP.ListItemCreationInformation());
  listItem.set_item('Title', "My Announcement");
  listItem.set_item("Author", userField);
  listItem.update();                

  clientContext.executeQueryAsync( 
    function (sender, args) {
      console.log('successfully updated');
    }, 
    function (sender, args) {
      console.log('Request failed, adding new list item');                  
    }
  );

}
1

Updating this field requires the UpdateOverwriteVersion method when working on the server side (see sample). Since this method (or the SystemUpdate method) is not available in the client OM, I am a bit sceptic that you can achieve your goal.

It's not clear, what you would like to achieve with this code:

var userField = user.get_id() + ";#" + user.get_loginName() + ";" + user.get_id() + ";#" + user.get_loginName();

Is it a copy-paste failure, or you would like to store the same user twice in the same single user field?

why not simply:

var userField = user.get_id() + ";#" + user.get_loginName();
  • thank for that, yes it was a copy paste error I meant var userField = user.get_id() + ";#" + user.get_loginName(); will update my question. I think I have found a way to do it, by first querying the user with web.ensureUser(userName). I will post an answer once I have it working – svnm Mar 4 '15 at 0:42
1

You could utilize SP.FieldUserValue.fromUser Method for that purpose, for example:

var authorVal = SP.FieldUserValue.fromUser(userName);
listItem.set_item('Author', authorVal); 

Complete example

var properties = {};
properties['Title'] = 'Request N#789';
properties['Author'] = SP.FieldUserValue.fromUser('i:0#.f|membership|username@tenant.onmicrosoft.com');



createListItem('Requests',properties,
     function(item) {
          console.log('Request has been created');        
     },
     function logError(sender, args) {
        console.log(args.get_message());
     }
   );

where

function createListItem(listTitle,itemProperties,success,error)
{
    var context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(listTitle);
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);
    for(var propName in itemProperties) {
       listItem.set_item(propName, itemProperties[propName]) 
    }
    listItem.update();
    context.executeQueryAsync(
      function() {
          success(listItem);
      },
      error);
} 
  • Thanks for this, it looks like a good solution, but is not working for me, possibly something to do with the i:0#.f part, it does not match up to what I get when I call user.get_loginName(). So for now I am using the solution to get the id from the user name, and then get the user field by id, I am passing in a callback to update my list item, so I just need to call getUser("steven.martin", function () { /* update list item */}) – svnm Mar 4 '15 at 22:55
1

In the end I did it like this, although I think Vadim's approach may also be correct, I couldn't get it to work myself.

get user id by name

function getUserId = function (userName) {              

  var clientContext = SP.ClientContext.get_current();
  var web = clientContext.get_web();
  var currentUser = web.ensureUser(userName);
  clientContext.load(web);
  clientContext.load(currentUser);
  clientContext.executeQueryAsync(function () {
    var userid = currentUser.get_id();
      // now you have the id, get the user field to update author
      getUserById(userid);
    }, function (sender, args) {
      console.log('failed to get the current user');
    }); 
}

get user fields by id

function getUserById(userid) {
  var context = new SP.ClientContext();
  var user = context.get_web().getUserById(30); // e.g. user id = 30
  context.load(user);
  context.executeQueryAsync( 
    function () {
      // now you have the user id and correct login name, update author
      var userField = user.get_id() + ";#" + user.get_loginName();
      updateUser(userField);
     },
     function (sender, args) {
       console.log('Error retrieving user properties');
     }
  );
}

update user/ author field

function updateUser(userField) {
  var clientContext = new SP.ClientContext("/");
  var list = clientContext.get_web().get_lists().getByTitle("Announcments");
  var listItem = {};
  listItem = list.addItem(new SP.ListItemCreationInformation());
  listItem.set_item('Title', "My Announcement");
  listItem.set_item("Author", userField);
  listItem.update();                

  clientContext.executeQueryAsync( 
    function (sender, args) {
      console.log('successfully updated');
    }, 
    function (sender, args) {
      console.log('Request failed, adding new list item');                  
    }
  );

}

So calling getUserId("steven.martin") will update in this case the list item with the author field, rather than giving the author who actually created the item.

Note: I actually passed in a callback function to getUserId and getUserById so I could call the function and on success get the user field which I can use to update the list item. So I can call a general getUser function like this getUser("steven.martin", function () { /* update list item */})

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.