2

I want to add item to list where Title is equal to current user ID by JavaScript Object Model.

As far as I know I first need to get currentUserID and I wrote the following code

currentUser = web.get_currentUser();
clientContext.load(currentUser);
clientContext.executeQueryAsync(
  Function.createDelegate(this, onQuerySucceeded),
  Function.createDelegate(this, onQueryFailed)
);

function onQuerySucceeded(){
    alert (currentUser.get_id());
}
function onQueryFailed(){
    alert("Fail!" + args.get_message() + "\n" + args.get_stackTrace());    
}

With following piece of code I can add item to the list

list = oWebsite.get_lists().getByTitle("MyList");
itemCreateInfo = new SP.ListItemCreationInformation();
currentUser = oWebsite.get_currentUser();
istItem = list.addItem(itemCreateInfo);
listItem.set_item("Title", "Current SPUser ID"); //here I'd like to write user's ID
now = new Date();
now.format("dd/M/yy h:mm tt");
listItem.set_item("Visit", now);
listItem.update();
userData = clientContext.load(listItem);
clientContext.executeQueryAsync(
            Function.createDelegate(this, onQuerySucceeded),
            Function.createDelegate(this, onQueryFailed)
            );

        function onQuerySucceeded() {
            alert("Success");
        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message());
        }

What I want is to replace string "Current SPUser ID" with actual user ID (currentUser.get_id()).

5

Place the second code section in a function and call it from the success function of the first passing the userid as a parameter.

4

It actually depends how to retrieve current User id

Suppose we have a function for adding List Item

function AddListItem(listTitle,itemProps,OnItemAdded)
{
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();


    var list = web.get_lists().getByTitle(listTitle);
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);

    for(var propName in itemProps) {
       listItem.set_item(propName, itemProps[propName]) 
    }

    listItem.update();
    context.load(listItem);
    context.executeQueryAsync(
        function() {
          OnItemAdded(listItem);           
        },
        function(sender, args) {
           OnItemAdded(null);
        }
    );
}

Retrieve current User Id via CSOM (JavaScipt)

In this case current user Id have to be retrieved first

function GetCurrentUserId(OnComplete) {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var currentUser = web.get_currentUser();
    context.load(currentUser);
    context.executeQueryAsync(
        function() {
            var userId = currentUser.get_id();
            OnComplete(userId);
        },
        function(sender, args) {
            OnComplete(null);
        }
    );  
}

and only then we can add item as demonstrated below

function Insert()
{
    //1
    GetCurrentUserId(function(userId){

        var itemProperties  = {'Title': userId}
        AddListItem('CustomList',itemProperties,function(){});      

    });
}
ExecuteOrDelayUntilScriptLoaded(Insert, 'SP.js');         

Retrieve current user Id from _spPageContextInfo

function Insert()
{
    var userId = _spPageContextInfo.userId;
    var itemProperties  = {'Title': userId}
    AddListItem('CustomList',itemProperties,function(){});
}
ExecuteOrDelayUntilScriptLoaded(Insert, 'SP.js');
  • 1
    Your answer clarified some points to me. tks! – egidiocs Mar 9 '16 at 4:00
1

First we will load the current user and then use it success method to add list item. Code example below

 this.currentUser = web.get_currentUser();
 clientContext.load(currentUser);
 clientContext.executeQueryAsync(
 Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);

function onQuerySucceeded(){
    alert (currentUser.get_id());
   //add list item code goes here.. Pass current users id as currentUser.get_id()
}
function onQueryFailed(){
   alert("Fail!" + args.get_message() + "\n" + args.get_stackTrace());    
}
1

Had to do this very thing yesterday. Firstly you need to create a variable to hold you userID

var userID;

Then in your document ready function call the sharePointReady function (or whatever you want to call it)

$(document).ready(function () { sharePointReady(); }

Then the funciton

// This function creates a context object which is needed to use the SharePoint object model
function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();

getUserName();
}

Then the rest

// This function prepares, loads, and then executes a SharePoint query to get the
// current users information
function getUserName() {
user = web.get_currentUser();
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'helloString' element with the user name
function onGetUserNameSuccess() {
fullUserName = user.get_title();
userID = user.get_id();
$('#message').text('Welcome back ' + fullUserName);
}

You see from mine i wanted to store both the Name and the ID for various purposes. Then your insert looks like this...

listItem.set_item("Title", fullUserName);

Hope this helps.

S

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.