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.
<div>
<p id="message">
<table>
<tr>
<td>New To Do Item</td>
<td> <input id="newToDoItem" type="text" /></td>
<td> <button id="addItemButton">Add</button></td>
</tr>
</table>
</p>
</div>
<div>
<ul id="ToDoItems"></ul>
</div>
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();
listCreationInfo.set_title("ToDoItems");
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
lists = web.get_lists();
var newList = lists.add(listCreationInfo);
context.load(newList);
context.executeQueryAsync();
}
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();
addToDoItem(toDoItemTitle);
event.preventDefault();
});
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)
listItem.update();
context.load(listItem);
context.executeQueryAsync();
}
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