Showing posts with label Add new item in SharePoint 2013 client object model. Show all posts
Showing posts with label Add new item in SharePoint 2013 client object model. Show all posts

Monday, May 27, 2013

Add current logged-in user to a new list item by using SharePoint 2013 Client Object Model

While working in SharePoint event registration with SharePoint-hosted app by using Client Side Object Model. In that code I had a requirement to add the current logged in user to list item. Here is the code to get the current logged-in user and add a new list item to the new list item.

var currentContext;
var web;
var user;
$(document).ready(init());

function init() {
//get current context
currentContext = SP.ClientContext.get_current();

//get current web details
web = currentContext.get_web();

getCurrentUser();
addNewItem();
}

function getCurrentUser() {
user = web.get_currentUser();
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFailed);
}

function onGetUserNameSuccess() {
//custom code with current logged in user
}

function onGetUserNameFailed(sender, args) {
//log the error
}

function addNewItem()
{
// get the list for your item
var list = context.get_web().get_lists().getByTitle("ListName");

// create a ListItemCreationInformation object
var itemCreateInfo = new SP.ListItemCreationInformation();

// add this item to the list
var newItem = list.addItem(itemCreateInfo);

// Create a UserValue and set the LookupId to the current user
var userValue = new SP.FieldUserValue();
userValue.LookupId = user.get_id();

// Create a LookupValue and set the lookupId to the id of an event
var eventValue = new SP.FieldLookupValue();
eventValue.set_lookupId($("#Lookup Coloumn").val()); 

newItem.set_item('Title', user); //internal names
newItem.set_item('EventLookup', eventValue);
newItem.update();

context.load(newItem);
context.executeQueryAsync(
Function.createDelegate(this, this.onAddNewItemSucceeded),
Function.createDelegate(this, this.onAddNewItemFailed)
);
}

function onAddNewItemSucceeded() {
//custom code when Item Added Successfully
}
function onAddNewItemFailed(sender, args) {
//log the error

}