Wednesday, October 28, 2015

Creating a SharePoint list and Adding List Items in SharePoint Apps

In my previous article I explained how to read from a SharePoint list available inside a SharePoint App site. In this article my focus would be on how to create a list inside the app and how to add list items to it. The same app I used in the previous example will be used here. Here is the code available in my Default.aspx file. It is simple just a textbox and a lable inside a HTM table and a div which includes an unordered list.

I will start having the same set of definitions in the top.

var context = SP.ClientContext.get_current();
var web = context.get_web();
var user = context.get_web().get_currentUser();
var lists = web.get_lists();

These need to be added before the definition of the function of App.js file

Here is the HTML content in the selected are.

<p id="message">
<td>New To Do Item</td>
<td> <input id="newToDoItem" type="text" /></td>
<td> <button id="addItemButton">Add</button></td>
<ul id="ToDoItems"></ul>

1. Creating the "ToDoItems" list

This is quite simple. All you need to do is creating an object of the SP.ListCreationInformation and then define the list name and the template. 

function createToDoList() {
var listCreationInfo = new SP.ListCreationInformation();

lists = web.get_lists();
var newList = lists.add(listCreationInfo);

Here I am using the no parameter constructor of the executeQueryAsync() method as I do not need to perform any action when the creation gets succeeded or not.

2. Adding list items to the "ToDoItems" list

Here we need to add an event listener to the click button of the addItemButton

$("#addItemButton").click(function(event) {
var toDoItemTitle = $('#newToDoItem').val();

Here we have called a function addToDoItem which takes the text of the textbox available as a parameter. 

function addToDoItem(title) {
var list = web.get_lists().getByTitle(toDoListTitle);

var itemCreationInformation = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreationInformation);
listItem.set_item('Title', title)


As we did in the list creation, here an instance of SP.ListItemCreationInformation is created. Then add the list item to the list by setting the list item title as the text entered in the textbox. Here also I have used the no parameter constructor of the executeQueryAsync() method. If needed you can add functions for success and fail and refresh the list items in the unordered HTML list.

A sample with much extended functionality is shared on the sample gallery and it can be viewed from here

No comments:

Post a Comment