There I have highlighted location when you can execute events, I hope it’s self-explanatory.
Accordingly I will show you’re my JavaScript object model, we start with Operator where I show just two functions read item and update item, rest of them will be omitted, but whole source code you can download from link at the end of this article.
readItem: function (id) {
$.ajax({
//getting only fields which are needed
url: _spPageContextInfo.webServerRelativeUrl +
"/_api/web/lists/getByTitle('Contacts')/getItemByStringId('" +
id + "')/?$select=FirstName,Title,WorkPhone,Email",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
//fill up your form
CRUDApp.FormFiller.fill(data.d.Title, data.d.FirstName, data.d.WorkPhone, data.d.Email);
},
error: function (err) {
alert(JSON.stringify(err));
}
});
},
update: function (id, lname, fname, wphone, wemail) {
$.ajax({
url: _spPageContextInfo.webServerRelativeUrl +
"/_api/web/lists/getByTitle('Contacts')/getItemByStringId('" +
id + "')",
type: "POST",
contentType: "application/json;odata=verbose",
//update only selected fields
data: JSON.stringify(
{
'__metadata': {
'type': 'SP.Data.ContactsListItem'
},
'Title': lname,
'FirstName': fname,
'WorkPhone': wphone,
'Email': wemail
}),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-Http-Method": "PATCH"
},
success: function (data) {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, false);
},
error: function (err) {
aler(JSON.stringify(err));
}
});
},
All the headers format is inspired from MSDN how to which you can find here. In the read item function, I have trimmed results just only for our fields and then in success branch fill form. At the second example of update item, I do create the JSON object with using helping method and put it in data branch. Next we have a look at Controller class which is responsible for consuming any events from our App.
//Namespace
window.CRUDApp = window.CRUDApp || {}
//Handle all user events
window.CRUDApp.Controller = {
init: function () {
//private literal properties
var sNewContact = "#newContact", sNewButton = "#newButton",
sSaveButton = "#saveButton", sCancelButton = "#cancelButton",
sLastName = "#lastName", sFirstName = "#firstName",
sWorkPhone = "#workPhone", sWorkEmail = "#workEmail"
$(sNewContact).click(function () {
SP.UI.ModalDialog.showModalDialog({
url: "AddContact.aspx?IsDlg=1",
title: "New Contact",
allowMaximize: false,
showClose: true,
width: 400,
height: 300,
dialogReturnValueCallback: CRUDApp.Operator.readAll
});
});
$(sNewButton).click(function () {
CRUDApp.Operator.create($(sLastName).val(), $(sFirstName).val(),
$(sWorkPhone).val(), $(sWorkEmail).val());
});
$(sSaveButton).click(function () {
var id = getQueryStringValue("Id");
CRUDApp.Operator.update(id, $(sLastName).val(),
$(sFirstName).val(), $(sWorkPhone).val(),
$(sWorkEmail).val());
});
$(sCancelButton).click(function () {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, false);
});
},
editItem: function (id) {
SP.UI.ModalDialog.showModalDialog({
url: "EditContact.aspx?IsDlg=1&Id=" + id,
title: "Edit Contact",
allowMaximize: false,
showClose: true,
width: 400,
height: 300,
dialogReturnValueCallback: CRUDApp.Operator.readAll
});
},
readItem: function (id) {
SP.UI.ModalDialog.showModalDialog({
url: "DisplayContact.aspx?IsDlg=1&Lock=1&Id=" + id,
title: "Display Contact",
allowMaximize: false,
showClose: true,
width: 400,
height: 300,
dialogReturnValueCallback: null
});
},
deleteItem: function (id) {
CRUDApp.Operator.remove(id);
}
}
In the initialization function we registered events by JQuery on our button with particular functionality, you can see most of them reference functionality from Operator class which covers communication. We are using SharePoint UI Modal dialogs for wrapping our pages. As a last piece of code I show you how we build our table based on template.
//Namespace
window.CRUDApp = window.CRUDApp || {}
//Render results in a table
window.CRUDApp.TableRenderer = function () {
//private members
var element, data, header, rowTempale, displayDiv = 'undefined'
var sRowTemplate = "rowTemplate"
init = function () {
//header template
header = "<thead><th> </th><th>Last Name</th><th>First Name</th>" +
"<th>Work Phone</th><th>Work Email</th><th> </th><th> </th></thead>";
//template for each row
rowTemplate = "<tr><td><a href=\"javascript:CRUDApp.Controller.readItem('{{=Id}}');\">" +
"<img src='/_layouts/15/images/icgen.gif' border='0'/></a></td>" +
"<td>{{=Title}}</td><td>{{=FirstName}}</td><td>{{=WorkPhone}}</td><td>{{=Email}}</td>" +
"<td><a href=\"javascript:CRUDApp.Controller.editItem('{{=Id}}');\">" +
"<img src='/_layouts/15/images/edit.gif' border='0'/></a></td>" +
"<td><a href=\"javascript:CRUDApp.Controller.deleteItem('{{=Id}}');\">" +
"<img src='/_layouts/15/images/delete.gif' border='0'/></a></td></tr>";
//find our table
element = $("<table>", { id: "contactsTable" });
//apply template
$.template(sRowTemplate, rowTemplate);
},
set_data = function (v) { data = v; },
set_displayDiv = function (v) { displayDiv = v; },
render = function () {
element.empty();
element.append($(header));
element.append($.render(data, sRowTemplate));
displayDiv.append(element);
}
//public interface
return {
init: init,
set_data: set_data,
set_displayDiv: set_displayDiv,
render: render
};
}();
The main attention is required to our template there are located JavaScript calls from where we call function in our Controller class. The whole source code is located on my Skydrive here.
The Conclusion
In this particular project I have attempted to show you, how potentially we can design solution and also discover SharePoint REST services. I hope you understand all well. Big thanks for inspiration to Scot Hillier’s codeplex project. The purpose of this article was not stole source code, but describe it and explore it.