Here are the steps:
Step 1: SHA Project folder structure.
Step 2: App Web List Creation Steps.
Firstly add simple list into SHA project. Here are the steps to create List into SHA project.
In this example I created custom list named “Customers” as in the following,
Elements.xml File code- it adds data into List.
- <?xml version="1.0" encoding="utf-8"?>
- <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
- <ListInstance Title="Customers" OnQuickLaunch="TRUE" TemplateType="105" FeatureId="00bfea71-7e6d-4186-9ba8-c047ac750105" Url="Lists/Customers" Description="My List Instance">
- <Data>
- <Rows>
- <Row>
- <Field Name="FirstName">Rupali</Field>
- <Field Name="Title">Shinde</Field>
- <Field Name="WorkPhone">(123)456-6789</Field>
- </Row>
- <Row>
- <Field Name="FirstName">Vishnu</Field>
- <Field Name="Title">Jadhav</Field>
- <Field Name="WorkPhone">(143)867-5309</Field>
- </Row>
- <Row>
- <Field Name="FirstName">DJ</Field>
- <Field Name="Title">Jadhav</Field>
- <Field Name="WorkPhone">(800)LUV-AZUR</Field>
- </Row>
- <Row>
- <Field Name="FirstName">Summit</Field>
- <Field Name="Title">Jadhav</Field>
- <Field Name="WorkPhone">(888)123-5677</Field>
- </Row>
- <Row>
- <Field Name="FirstName">Kiran</Field>
- <Field Name="Title">Jadhav</Field>
- <Field Name="WorkPhone">(888)GOT-OAUTH</Field>
- </Row>
- <Row>
- <Field Name="FirstName">Shrikant</Field>
- <Field Name="Title">Shinde</Field>
- <Field Name="WorkPhone">(813)813-8133</Field>
- </Row>
- <Row>
- <Field Name="FirstName">Seema</Field>
- <Field Name="Title">Jadhav</Field>
- <Field Name="WorkPhone">(800)BIG-TULS</Field>
- </Row>
- </Rows>
- </Data>
- </ListInstance>
- </Elements>
Step 3: User Interface designing steps.
Home page of application is having “Add New Customer “ button, which shows user entry form to fill user details.
User Details Grid – this grid will show user details with Edit, Delete and Display button into it.
- <%@ Page Language="C#" MasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
- SharePoint-hosted App REST API Demo
- </asp:Content>
- <asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
- Using the REST API from Client-side JavaScript
- </asp:Content>
- <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
- <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
- <script type="text/javascript" src="../Scripts/jquery-1.6.2.min.js"></script>
- <script type="text/javascript" src="../Scripts/jsrender.js"></script>
- <script type="text/javascript" src="../Scripts/App.js"></script>
- </asp:Content>
- <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
- <div id="toolbar">
- <input type="button" id="cmdAddNewCustomer" value="Add New Customer" class="ms-ButtonHeightWidth" />
- </div>
- <div id="results" />
- </asp:Content>
Output
Step 4: Grid Data filling steps – the following code is used to fill GridView.
- var hostweburl;
- var appweburl;
- $(function () {
- // register event handlers on page
- $("#cmdAddNewCustomer").click(onAddCustomer);
- $("#results").append($("<img>", { src: "_layouts/images/gears_anv4.gif" }));
- // Get the URI decoded URLs.
- hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
- appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
- var scriptbase = hostweburl + "/_layouts/15/";
- $.getScript(scriptbase + "SP.RequestExecutor.js", getCustomers);
- });
- function getCustomers() {
- $("#results").empty();
- $("<img>", { "src": "/_layouts/images/GEARS_AN.GIF" }).appendTo("#results");
- var executor = new SP.RequestExecutor(appweburl);
- var FullURL = appweburl + "/_api/web/lists/getbytitle('Customers')/items";
- executor.executeAsync(
- {
- url: FullURL,
- method: "GET",
- headers: {
- "accept": "application/json;odata=verbose",
- "content-type": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val()
- },
- success: onDataReturned,
- error: errorHandler
- }
- );
- }
- function errorHandler(data, errorCode, errorMessage) {
- document.getElementById("results").innerText = "Could not complete cross-domain call: " + errorMessage;
- }
- function onDataReturned(data) {
- $("#results").empty();
- var jsonObject = JSON.parse(data.body);
- var odataResults = jsonObject.d.results;
- // set rendering template
- var tableHeader = "<thead>" +
- "<td>Last Name</td>" +
- "<td>First Name</td>" +
- "<td>Work Phone</td>" +
- "<td> </td>" +
- "<td> </td>" +
- "<td> </td>" +
- "</thead>";
- var table = $("<table>", { id: "customersTable" }).append($(tableHeader));
- var renderingTemplate = "<tr>" +
- "<td>{{>Title}}</td>" +
- "<td>{{>FirstName}}</td>" +
- "<td>{{>WorkPhone}}</td>" +
- "<td><a href='javascript: onShowCustomerDetail({{>Id}});'><img src='_layouts/images/DETAIL.gif' alt='Show Detail' /></a></td>" +
- "<td><a href='javascript: onUpdateCustomer({{>Id}});'><img src='_layouts/images/EDITITEM.gif' alt='Edit' /></a></td>" +
- "<td><a href='javascript: onDeleteCustomer({{>Id}});'><img src='_layouts/images/DELITEM.gif' alt='Delete' /></a></td>" +
- "</tr>";
- $.templates({ "tmplTable": renderingTemplate });
- table.append($.render.tmplTable(odataResults));
- $("#results").append(table);
- }
Step 5: Add new customer
EditCustomer.aspx file contains code for New Customer Popup.
- <%@ Page Language="C#" MasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
- <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
- <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
- <SharePoint:ScriptLink name="SP.UI.Dialog.js" runat="server" Defer="false" LoadAfterUI="true" Localizable="false" />
- <SharePoint:ScriptLink name="sp.js" runat="server" Defer="false" LoadAfterUI="true" Localizable="false" />
- <script type="text/javascript" src="../Scripts/jquery-1.6.2.js"></script>
- <script type="text/javascript" src="../Scripts/EditCustomer.js"></script>
- </asp:Content>
- <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
- <div class="dialog_input_section">
- <table id="customerEditTable">
- <tr>
- <td>First Name:</td>
- <td>
- <input id="txtFirstName" /></td>
- </tr>
- <tr>
- <td>Last Name:</td>
- <td>
- <input id="txtLastName" /></td>
- </tr>
- <tr>
- <td>Work Phone:</td>
- <td>
- <input id="txtWorkPhone" /></td>
- </tr>
- </table>
- </div>
- <div class="dialog_button_section">
- <input type="button" id="cmdOK" value="Save" class="ms-ButtonHeightWidth" />
- <input type="button" id="cmdCancel" value="Cancel" class="ms-ButtonHeightWidth" />
- </div>
- </asp:Content>
App.JS file contains the following code to open popup.
- $("#cmdAddNewCustomer").click(onAddCustomer);
Step 6: Update Customer
Inside GridView, edit button is provided to update existing customer details.
Code:
- function onUpdateCustomer(customer) {
- var executor = new SP.RequestExecutor(appweburl);
- var FullURL = appweburl + "/_api/web/lists/getbytitle('Customers')/items(" + customer + ")";
- executor.executeAsync(
- {
- url: FullURL,
- method: "GET",
- headers: {
- "accept": "application/json;odata=verbose",
- "content-type": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val()
- },
- success: onCustomerReturned,
- error: errorHandler
- }
- );
- }
Output
Step 7: Delete Customer
Inside GridView, delete button is provided to delete existing customer details.
Code
- function onDeleteCustomer(customer) {
- var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Customers')/items(" + customer + ")";
- var requestHeaders = {
- "accept": "application/json",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "If-Match": "*"
- }
- $.ajax({
- url: requestUri,
- type: "DELETE",
- contentType: "application/json",
- headers: requestHeaders,
- success: onSuccess,
- error: onError
- });
- }
Step 8: View Customer Details.
Inside GridView, view button is provided to view existing customer details.
- function onShowCustomerDetail(customer) {
- var customerItemEditUrl = _spPageContextInfo.webAbsoluteUrl +
- "/Lists/Customers/DispForm.aspx?ID=" + customer;
- var dialogOptions = {
- url: customerItemEditUrl,
- title: "Customer Detail",
- dialogReturnValueCallback: getCustomers
- };
- SP.UI.ModalDialog.showModalDialog(dialogOptions);
- }
Output
When view form is open in browser and if you change user details there itself it gets updated and final result get rendered on screen.
Full Source Code
- var hostweburl;
- var appweburl;
- $(function () {
- // register event handlers on page
- $("#cmdAddNewCustomer").click(onAddCustomer);
- $("#results").append($("<img>", { src: "_layouts/images/gears_anv4.gif" }));
- // Get the URI decoded URLs.
- hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
- appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
- var scriptbase = hostweburl + "/_layouts/15/";
- $.getScript(scriptbase + "SP.RequestExecutor.js", getCustomers);
- });
- function getCustomers() {
- $("#results").empty();
- $("<img>", { "src": "/_layouts/images/GEARS_AN.GIF" }).appendTo("#results");
- var executor = new SP.RequestExecutor(appweburl);
- var FullURL = appweburl + "/_api/web/lists/getbytitle('Customers')/items";
- executor.executeAsync(
- {
- url: FullURL,
- method: "GET",
- headers: {
- "accept": "application/json;odata=verbose",
- "content-type": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val()
- },
- success: onDataReturned,
- error: errorHandler
- }
- );
- }
- function errorHandler(data, errorCode, errorMessage) {
- document.getElementById("results").innerText = "Could not complete cross-domain call: " + errorMessage;
- }
- function onDataReturned(data) {
- $("#results").empty();
- var jsonObject = JSON.parse(data.body);
- var odataResults = jsonObject.d.results;
- // set rendering template
- var tableHeader = "<thead>" +
- "<td>Last Name</td>" +
- "<td>First Name</td>" +
- "<td>Work Phone</td>" +
- "<td> </td>" +
- "<td> </td>" +
- "<td> </td>" +
- "</thead>";
- var table = $("<table>", { id: "customersTable" }).append($(tableHeader));
- var renderingTemplate = "<tr>" +
- "<td>{{>Title}}</td>" +
- "<td>{{>FirstName}}</td>" +
- "<td>{{>WorkPhone}}</td>" +
- "<td><a href='javascript: onShowCustomerDetail({{>Id}});'><img src='_layouts/images/DETAIL.gif' alt='Show Detail' /></a></td>" +
- "<td><a href='javascript: onUpdateCustomer({{>Id}});'><img src='_layouts/images/EDITITEM.gif' alt='Edit' /></a></td>" +
- "<td><a href='javascript: onDeleteCustomer({{>Id}});'><img src='_layouts/images/DELITEM.gif' alt='Delete' /></a></td>" +
- "</tr>";
- $.templates({ "tmplTable": renderingTemplate });
- table.append($.render.tmplTable(odataResults));
- $("#results").append(table);
- }
- function onShowCustomerDetail(customer) {
- var customerItemEditUrl = _spPageContextInfo.webAbsoluteUrl +
- "/Lists/Customers/DispForm.aspx?ID=" + customer;
- var dialogOptions = {
- url: customerItemEditUrl,
- title: "Customer Detail",
- dialogReturnValueCallback: getCustomers
- };
- SP.UI.ModalDialog.showModalDialog(dialogOptions);
- }
- function onAddCustomer(event) {
- var dialogArgs = {
- command: "Add"
- };
- var dialogOptions = {
- url: "EditCustomer.aspx",
- title: "Add New Customer",
- width: "480px",
- args: dialogArgs,
- dialogReturnValueCallback: saveNewCustomer
- };
- SP.UI.ModalDialog.showModalDialog(dialogOptions);
- }
- function saveNewCustomer(dialogResult, returnValue) {
- if (dialogResult == SP.UI.DialogResult.OK) {
- // get data from dialog for new customer
- var LastName = returnValue.LastName;
- var FirstName = returnValue.FirstName;
- var WorkPhone = returnValue.WorkPhone;
- var requestUri = _spPageContextInfo.webAbsoluteUrl +
- "/_api/Web/Lists/getByTitle('Customers')/items/";
- var requestHeaders = {
- "accept": "application/json",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- }
- var customerData = {
- Title: LastName,
- FirstName: FirstName,
- WorkPhone: WorkPhone
- };
- requestBody = JSON.stringify(customerData);
- $.ajax({
- url: requestUri,
- type: "Post",
- contentType: "application/json",
- headers: requestHeaders,
- data: requestBody,
- success: onSuccess,
- error: onError
- });
- }
- }
- function onDeleteCustomer(customer) {
- var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Customers')/items(" + customer + ")";
- var requestHeaders = {
- "accept": "application/json",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "If-Match": "*"
- }
- $.ajax({
- url: requestUri,
- type: "DELETE",
- contentType: "application/json",
- headers: requestHeaders,
- success: onSuccess,
- error: onError
- });
- }
- function onUpdateCustomer(customer) {
- var executor = new SP.RequestExecutor(appweburl);
- var FullURL = appweburl + "/_api/web/lists/getbytitle('Customers')/items(" + customer + ")";
- executor.executeAsync(
- {
- url: FullURL,
- method: "GET",
- headers: {
- "accept": "application/json;odata=verbose",
- "content-type": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val()
- },
- success: onCustomerReturned,
- error: errorHandler
- }
- );
- }
- function onCustomerReturned(data) {
- var jsonObject = JSON.parse(data.body);
- var dialogArgs = {
- command: "Update",
- Id: jsonObject.d.Id,
- LastName: jsonObject.d.Title,
- FirstName: jsonObject.d.FirstName,
- WorkPhone: jsonObject.d.WorkPhone,
- etag: jsonObject.d.__metadata.etag
- };
- var dialogOptions = {
- url: "EditCustomer.aspx",
- title: "Update Customer",
- width: "480px",
- args: dialogArgs,
- dialogReturnValueCallback: updateCustomer
- };
- SP.UI.ModalDialog.showModalDialog(dialogOptions);
- }
- function updateCustomer(dialogResult, returnValue) {
- if (dialogResult == SP.UI.DialogResult.OK) {
- var Id = returnValue.Id;
- var FirstName = returnValue.FirstName;
- var LastName = returnValue.LastName;
- var WorkPhone = returnValue.WorkPhone;
- var etag = returnValue.etag;
- var requestUri = appweburl + "/_api/web/lists/getbytitle('Customers')/items(" + Id + ")";
- var requestHeaders = {
- "accept": "application/json",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "X-HTTP-Method": "MERGE",
- "If-Match": etag
- }
- var customerData = {
- Title: LastName,
- FirstName: FirstName,
- WorkPhone: WorkPhone
- };
- requestBody = JSON.stringify(customerData);
- $.ajax({
- url: requestUri,
- type: "POST",
- contentType: "application/json",
- headers: requestHeaders,
- data: requestBody,
- success: onSuccess,
- error: onError
- });
- }
- }
- function onSuccess(data, request) {
- getCustomers();
- }
- function onError(error) {
- $("#results").empty();
- $("#results").text("ADD ERROR: " + JSON.stringify(error));
- }
- function getQueryStringParameter(paramToRetrieve) {
- var strParams = "";
- var params = document.URL.split("?")[1].split("&");
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve)
- return singleParam[1];
- }
- }
App.css
- .ms-siteicon-a {
- background-image: url(images/SiteIcon.gif);
- background-repeat: no-repeat;
- width: 75px;
- height: 75px;
- }
- .ms-siteicon-img {
- display: none;
- }
- .ms-core-siteTitle span a {
- font-size: 18px;
- }
- #customersTable {
- background-color: #999;
- border-collapse: collapse;
- }
- #customersTable thead td {
- background-color: #333;
- color: White;
- }
- #customersTable td {
- color: #222;
- border: 1px black solid;
- padding: 4px;
- background-color: White;
- border-collapse: collapse;
- }
- #resultsTable tr td {
- color: #333;
- padding: 4px;
- border-collapse: collapse;
- border: 1px solid black;
- background-color: White;
- font-size: 32px;
- }
- #toolbar {
- margin: 4px;
- padding: 8px;
- background-color: #ccc;
- }
- #results {
- padding: 8px;
- font-size: 12px;
- }
- #results table {
- margin: 8px
- }
- #results table, #results table td {
- border-collapse: collapse;
- border: 1px #444 solid;
- padding: 2px 8px 2px 4px;
- font-size: 20px;
- }
- #results h2 {
- font-size: 18px;
- color: #999;
- border-bottom: 1px solid #999;
- margin-top: 8px;
- margin-bottom: 4px;
- }
- .ms-dialog #s4-ribbonrow {
- display: none;
- }
- .ms-dlgTitle {
- background-image: url("images/logo16.gif");
- background-repeat: no-repeat;
- background-position: 8px, 4px;
- background-color: black;
- padding: 1px;
- }
- h1.ms-dlgTitleText {
- margin-left: 28px;
- margin-top: 4px;
- }
- .ms-dlgTitle h1 {
- font-size: 1.4em;
- color: white;
- }
- #dlgTitleBtns {
- margin-top: 4px;
- margin-right: 8px;
- }
- .ms-dlgTitle {
- padding-bottom: 4px;
- padding-left: 8px;
- }
- .ms-dlgTitle h1 {
- font-size: 1.8em;
- }
- .dialog_input_section {
- padding-top: 4px;
- }
- .dialog_input_section_title {
- margin-top: 8px;
- color: black;
- border-bottom: solid black 1px;
- margin-bottom: 8px;
- }
- .dialog_button_section {
- margin-top: 16px;
- border-top: solid #CCC 2px;
- padding-top: 8px;
- text-align: right;
- }
- .ms-dlgContent {
- padding-bottom: 2px;
- }
- .ms-dlgFrameContainer {
- padding-top: 4px;
- padding-left: 8px;
- padding-right: 8px;
- padding-bottom: 0px;
- }
1-http://www.dotnetcurry.com/sharepoint/1041/rest-apis-sharepoint-crud-database
2-http://ukreddysharepoint2010.blogspot.in/2015/01/how-to-crud-operation-in-sharepoint.html
3-http://blog.ch.atosconsulting.com/performing-rest-operations-on-host-webs-from-sharepoint-hosted-apps/
No comments:
Post a Comment