SlideShare una empresa de Scribd logo
1 de 14
SharePoint Online: Completing Basic
Operations using NAPA tool
2013
FLEXMIND SOLUTIONS
WWW.FLEXMINDSOLUTIONS.COM
FLEXMIND SOLUTIONS | www.flexmindsolutions.com
In this Article we are going to show you how we can perform CRUD operation in SharePoint online using
NAPA tool.
Napa tool SharePoint online development, -- how to install it
Create the list in the app web –
Performing read write update operation
Then trying to read the list item from host URL
Then to work on client web part to show the detail
Ref: http://msdn.microsoft.com/en-us/library/jj163201.aspx
http://msdn.microsoft.com/en-us/library/jj163201.aspx
http://msdn.microsoft.com/en-us/library/fp179912.aspx
http://msdn.microsoft.com/en-us/library/office/apps/jj164022.aspx
http://blogs.msdn.com/b/uksharepoint/archive/2013/02/22/manipulating-list-items-in-sharepoint-
hosted-apps-using-the-rest-api.aspx
Open the Napa development tool, this will ask to create a new project or you can work on previously
existing project
In this blog, I am going to discuss about the basicCreate, Read and Delete operationon the list created in
the app web hosted on the hosted SharePoint developer site.
Check the Napa online developer tool, how the content is organized for you before you began with the
development, here we have Content folder where you can put in all the Custom CSS, Images, Pages which
contain default.aspx which is set up as a start page to run when the app is loaded and finally the script
folder which contain all the script.
Office 365 SharePoint farm, support only SharePoint hosted app model, so application development done
here is using JavaScript (with the SharePoint 2013 JSOM library) and HTML
Open the default.aspx and add the following content to it.
When you try to run your application, it will appear something like this
Add a JavaScript file and name it as AppWeb.js.
Add this JavaScript reference to the default.aspx like this:
In the script shown below we are calling JavaScript anonymous function, which will be called when
Default.aspx page loaded.
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var web = context.get_web();
var lists = web.get_lists();
varlistItemCollection;
varhostweburl;
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function () {
hostweburl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl"));
//alert(hostweburl);
getUserName();
$("#getListCount").click(function (event) {
getWebProperties();
event.preventDefault();
});
$("#createlistbutton").click(function (event) {
createlist();
event.preventDefault();
});
$("#deletelistbutton").click(function (event) {
deletelist();
event.preventDefault();
});
displayLists();
$("#createitembutton").click(function (event) {
createitem();
event.preventDefault();
});
$("#deleteitembutton").click(function (event) {
deleteitem();
event.preventDefault();
});
// Update the list items dropdown when a new list
// is selected in the Lists dropdown.
$("#selectlistbox").change(function (event) {
getitems();
event.preventDefault();
});
});
//SP.SOD.executeFunc('core.js', 'SP.ClientContext', createHostWebURLofAPP);
functiongetQueryStringParameter(paramToRetrieve) {
varparams =
document.URL.split("?")[1].split("&");
varstrParams = "";
for (vari = 0; i<params.length; i = i + 1) {
varsingleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
returnsingleParam[1];
}
}
functiongetWebProperties() {
// Get the number of lists in the current web.
context.load(web);
context.load(lists);
context.executeQueryAsync(onWebPropsSuccess, onWebPropsFail);
}
functiononWebPropsSuccess(sender, args) {
alert('Number of lists in web: ' + lists.get_count() + web.get_url());
}
functiononWebPropsFail(sender, args) {
alert('Failed to get list. Error: ' + args.get_message());
}
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
functiongetUserName() {
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
functiononGetUserNameSuccess() {
$('#message').text('Hello ' + user.get_title());
}
// This function is executed if the above call fails
functiononGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
functiondisplayLists() {
// Get the available SharePoint lists, and then set them into
// the context.
lists = web.get_lists();
context.load(lists);
context.executeQueryAsync(onGetListsSuccess, onGetListsFail);
}
functiononGetListsSuccess(sender, args) {
// Success getting the lists. Set references to the list
// elements and the list of available lists.
varlistEnumerator = lists.getEnumerator();
varselectListBox = document.getElementById("selectlistbox");
if (selectListBox.hasChildNodes()) {
while (selectListBox.childNodes.length>= 1) {
selectListBox.removeChild(selectListBox.firstChild);
}
}
// Traverse the elements of the collection, and load the name of
// each list into the dropdown list box.
while (listEnumerator.moveNext()) {
varselectOption = document.createElement("option");
selectOption.value = listEnumerator.get_current().get_title();
selectOption.innerHTML = listEnumerator.get_current().get_title();
selectListBox.appendChild(selectOption);
}
}
functiononGetListsFail(sender, args) {
// Lists couldn’t be loaded - display error.
alert('Failed to get list. Error: ' + args.get_message());
}
functioncreatelist() {
// Create a generic SharePoint list with the name that the user specifies.
varlistCreationInfo = newSP.ListCreationInformation();
varlistTitle = document.getElementById("createlistbox").value;
listCreationInfo.set_title(listTitle);
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
lists = web.get_lists();
varnewList = lists.add(listCreationInfo);
context.load(newList);
context.executeQueryAsync(onListCreationSuccess, onListCreationFail);
}
functiononListCreationSuccess() {
displayLists();
}
functiononListCreationFail(sender, args) {
alert('Failed to create the list. ' +args.get_message());
}
functiondeletelist() {
// Delete the list that the user specifies.
varselectListBox = document.getElementById("selectlistbox");
varselectedListTitle = selectListBox.value;
varselectedList = web.get_lists().getByTitle(selectedListTitle);
selectedList.deleteObject();
context.executeQueryAsync(onDeleteListSuccess, onDeleteListFail);
}
functiononDeleteListSuccess() {
displayLists();
}
functiononDeleteListFail(sender, args) {
alert('Failed to delete the list. ' +args.get_message());
}
functioncreateitem() {
// Retrieve the list that the user chose, and add an item to it.
varselectListBox = document.getElementById("selectlistbox");
varselectedListTitle = selectListBox.value;
varselectedList = web.get_lists().getByTitle(selectedListTitle);
varlistItemCreationInfo = newSP.ListItemCreationInformation();
varnewItem = selectedList.addItem(listItemCreationInfo);
varlistItemTitle = document.getElementById("createitembox").value;
newItem.set_item('Title', listItemTitle);
newItem.update();
context.load(newItem);
context.executeQueryAsync(onItemCreationSuccess, onItemCreationFail);
}
functiononItemCreationSuccess() {
// Refresh the list of items.
getitems();
}
functiononItemCreationFail(sender, args) {
// The item couldn’t be created – display an error message.
alert('Failed to create the item. ' +args.get_message());
}
functiondeleteitem() {
// Delete the item that the user chose.
varselectListBox = document.getElementById("selectlistbox");
varselectedListTitle = selectListBox.value;
varselectedList = web.get_lists().getByTitle(selectedListTitle);
varselectItemBox = document.getElementById("selectitembox");
varselectedItemID = selectItemBox.value;
varselectedItem = selectedList.getItemById(selectedItemID);
selectedItem.deleteObject();
selectedList.update();
context.load(selectedList);
context.executeQueryAsync(onDeleteItemSuccess, onDeleteItemFail);
}
functiononDeleteItemSuccess() {
// Refresh the list of items.
getitems();
}
functiononDeleteItemFail(sender, args) {
// The item couldn’t be deleted – display an error message.
alert('Failed to delete the item. ' +args.get_message());
}
functiongetitems() {
// Using a CAML query, get the items in the list that the user chose, and
// set the context to the collection of list items.
varselectListBox = document.getElementById("selectlistbox");
varselectedList = selectListBox.value;
varselectedListTitle = web.get_lists().getByTitle(selectedList);
varcamlQuery = newSP.CamlQuery();
camlQuery.set_viewXml("<View><ViewFields>" +
"<FieldRef Name='ID' />" +
"<FieldRef Name='Title' />" +
"</ViewFields></View>')");
listItemCollection = selectedListTitle.getItems(camlQuery);
context.load(listItemCollection, "Include(Title, ID)");
context.executeQueryAsync(onGetItemsSuccess, onGetItemsFail);
}
functiononGetItemsSuccess(sender, args) {
// The list items were retrieved.
// Show all child nodes.
varlistItemEnumerator = listItemCollection.getEnumerator();
varselectItemBox = document.getElementById("selectitembox");
if (selectItemBox.hasChildNodes()) {
while (selectItemBox.childNodes.length>= 1) {
selectItemBox.removeChild(selectItemBox.firstChild);
}
}
while (listItemEnumerator.moveNext()) {
varselectOption = document.createElement("option");
selectOption.value = listItemEnumerator.get_current().get_item('ID');
selectOption.innerHTML = listItemEnumerator.get_current().get_item('Title');
selectItemBox.appendChild(selectOption);
}
}
functiononGetItemsFail(sender, args) {
// The list items couldn’t be retrieved - display an error message.
alert('Failed to get items. Error: ' + args.get_message());
}
})();
When you run the project it will upload the new app package to your SharePoint online developer hosted
web and open up App Web page
Now here we will create a new list say name it as “Contacts” and then click on create list
Now let’s add a new item to the list Contacts, in the JavaScript code shown above there we are adding
item to the Title field only.
Similarly we can delete the item from the list, select the item from the drop and click on Delete Selected
item
Update?
To read the data from list in the hosting web from app web:
'use strict';
varhostweburl;
varappweburl;
varclientContext;
$(document).ready(function () {
hostweburl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl"));
appweburl =
decodeURIComponent(
getQueryStringParameter('SPAppWebUrl')
);
alert(hostweburl);
alert(appweburl);
varscriptbase = hostweburl + '/_layouts/15/';
$.getScript(scriptbase+'SP.Runtime.js',function(){ $.getScript(scriptbase + 'SP.js',
function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', createHostWebURLofAPP); }
);});
});
functioncreateHostWebURLofAPP()
{
var factory;
varappContextSite;
varcollList;
clientContext= newSP.ClientContext(appweburl);
factory = newSP.ProxyWebRequestExecutorFactory(appweburl);
clientContext.set_webRequestExecutorFactory(factory);
appContextSite = newSP.AppContextSite(clientContext, hostweburl);
this.web = appContextSite.get_web();
collList = this.web.get_lists();
clientContext.load(this.web);
clientContext.load(collList);
//
// alert(hostweburl);
// clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed));
functiononQuerySucceeded() {
varlistInfo = '';
varlistEnumerator = collList.getEnumerator();
while (listEnumerator.moveNext()) {
varoList = listEnumerator.get_current();
listInfo += '<li>' + oList.get_title() + '</li>';
}
alert('Title: ' + this.web.get_title() +
' Description: ' + this.web.get_description());
}
functiononQueryFailed(sender, args) {
alert('Request failed. ' +args.get_message() +
'n' + args.get_stackTrace());
}
}
functiongetQueryStringParameter(paramToRetrieve) {
varparams =
document.URL.split("?")[1].split("&");
varstrParams = "";
for (vari = 0; i<params.length; i = i + 1) {
varsingleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
returnsingleParam[1];
}
}

Más contenido relacionado

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Destacado

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destacado (20)

Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 

Sharepoint Online App development using NAPA Tool.

  • 1. SharePoint Online: Completing Basic Operations using NAPA tool 2013 FLEXMIND SOLUTIONS WWW.FLEXMINDSOLUTIONS.COM FLEXMIND SOLUTIONS | www.flexmindsolutions.com
  • 2. In this Article we are going to show you how we can perform CRUD operation in SharePoint online using NAPA tool. Napa tool SharePoint online development, -- how to install it Create the list in the app web – Performing read write update operation Then trying to read the list item from host URL Then to work on client web part to show the detail Ref: http://msdn.microsoft.com/en-us/library/jj163201.aspx http://msdn.microsoft.com/en-us/library/jj163201.aspx http://msdn.microsoft.com/en-us/library/fp179912.aspx http://msdn.microsoft.com/en-us/library/office/apps/jj164022.aspx http://blogs.msdn.com/b/uksharepoint/archive/2013/02/22/manipulating-list-items-in-sharepoint- hosted-apps-using-the-rest-api.aspx
  • 3. Open the Napa development tool, this will ask to create a new project or you can work on previously existing project In this blog, I am going to discuss about the basicCreate, Read and Delete operationon the list created in the app web hosted on the hosted SharePoint developer site. Check the Napa online developer tool, how the content is organized for you before you began with the development, here we have Content folder where you can put in all the Custom CSS, Images, Pages which contain default.aspx which is set up as a start page to run when the app is loaded and finally the script folder which contain all the script. Office 365 SharePoint farm, support only SharePoint hosted app model, so application development done here is using JavaScript (with the SharePoint 2013 JSOM library) and HTML Open the default.aspx and add the following content to it.
  • 4. When you try to run your application, it will appear something like this Add a JavaScript file and name it as AppWeb.js. Add this JavaScript reference to the default.aspx like this:
  • 5. In the script shown below we are calling JavaScript anonymous function, which will be called when Default.aspx page loaded. 'use strict'; var context = SP.ClientContext.get_current(); var user = context.get_web().get_currentUser(); var web = context.get_web(); var lists = web.get_lists(); varlistItemCollection; varhostweburl; (function () { // This code runs when the DOM is ready and creates a context object which is // needed to use the SharePoint object model $(document).ready(function () { hostweburl = decodeURIComponent( getQueryStringParameter("SPHostUrl")); //alert(hostweburl); getUserName(); $("#getListCount").click(function (event) { getWebProperties(); event.preventDefault(); }); $("#createlistbutton").click(function (event) { createlist(); event.preventDefault(); }); $("#deletelistbutton").click(function (event) { deletelist(); event.preventDefault(); }); displayLists(); $("#createitembutton").click(function (event) {
  • 6. createitem(); event.preventDefault(); }); $("#deleteitembutton").click(function (event) { deleteitem(); event.preventDefault(); }); // Update the list items dropdown when a new list // is selected in the Lists dropdown. $("#selectlistbox").change(function (event) { getitems(); event.preventDefault(); }); }); //SP.SOD.executeFunc('core.js', 'SP.ClientContext', createHostWebURLofAPP); functiongetQueryStringParameter(paramToRetrieve) { varparams = document.URL.split("?")[1].split("&"); varstrParams = ""; for (vari = 0; i<params.length; i = i + 1) { varsingleParam = params[i].split("="); if (singleParam[0] == paramToRetrieve) returnsingleParam[1]; } } functiongetWebProperties() { // Get the number of lists in the current web. context.load(web); context.load(lists); context.executeQueryAsync(onWebPropsSuccess, onWebPropsFail); } functiononWebPropsSuccess(sender, args) { alert('Number of lists in web: ' + lists.get_count() + web.get_url()); } functiononWebPropsFail(sender, args) { alert('Failed to get list. Error: ' + args.get_message()); } // This function prepares, loads, and then executes a SharePoint query to get // the current users information functiongetUserName() { context.load(user);
  • 7. context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail); } // This function is executed if the above call is successful // It replaces the contents of the 'message' element with the user name functiononGetUserNameSuccess() { $('#message').text('Hello ' + user.get_title()); } // This function is executed if the above call fails functiononGetUserNameFail(sender, args) { alert('Failed to get user name. Error:' + args.get_message()); } functiondisplayLists() { // Get the available SharePoint lists, and then set them into // the context. lists = web.get_lists(); context.load(lists); context.executeQueryAsync(onGetListsSuccess, onGetListsFail); } functiononGetListsSuccess(sender, args) { // Success getting the lists. Set references to the list // elements and the list of available lists. varlistEnumerator = lists.getEnumerator(); varselectListBox = document.getElementById("selectlistbox"); if (selectListBox.hasChildNodes()) { while (selectListBox.childNodes.length>= 1) { selectListBox.removeChild(selectListBox.firstChild); } } // Traverse the elements of the collection, and load the name of // each list into the dropdown list box. while (listEnumerator.moveNext()) { varselectOption = document.createElement("option"); selectOption.value = listEnumerator.get_current().get_title(); selectOption.innerHTML = listEnumerator.get_current().get_title(); selectListBox.appendChild(selectOption); } } functiononGetListsFail(sender, args) { // Lists couldn’t be loaded - display error. alert('Failed to get list. Error: ' + args.get_message()); } functioncreatelist() { // Create a generic SharePoint list with the name that the user specifies. varlistCreationInfo = newSP.ListCreationInformation(); varlistTitle = document.getElementById("createlistbox").value;
  • 8. listCreationInfo.set_title(listTitle); listCreationInfo.set_templateType(SP.ListTemplateType.genericList); lists = web.get_lists(); varnewList = lists.add(listCreationInfo); context.load(newList); context.executeQueryAsync(onListCreationSuccess, onListCreationFail); } functiononListCreationSuccess() { displayLists(); } functiononListCreationFail(sender, args) { alert('Failed to create the list. ' +args.get_message()); } functiondeletelist() { // Delete the list that the user specifies. varselectListBox = document.getElementById("selectlistbox"); varselectedListTitle = selectListBox.value; varselectedList = web.get_lists().getByTitle(selectedListTitle); selectedList.deleteObject(); context.executeQueryAsync(onDeleteListSuccess, onDeleteListFail); } functiononDeleteListSuccess() { displayLists(); } functiononDeleteListFail(sender, args) { alert('Failed to delete the list. ' +args.get_message()); } functioncreateitem() { // Retrieve the list that the user chose, and add an item to it. varselectListBox = document.getElementById("selectlistbox"); varselectedListTitle = selectListBox.value; varselectedList = web.get_lists().getByTitle(selectedListTitle); varlistItemCreationInfo = newSP.ListItemCreationInformation(); varnewItem = selectedList.addItem(listItemCreationInfo); varlistItemTitle = document.getElementById("createitembox").value; newItem.set_item('Title', listItemTitle); newItem.update(); context.load(newItem); context.executeQueryAsync(onItemCreationSuccess, onItemCreationFail); } functiononItemCreationSuccess() {
  • 9. // Refresh the list of items. getitems(); } functiononItemCreationFail(sender, args) { // The item couldn’t be created – display an error message. alert('Failed to create the item. ' +args.get_message()); } functiondeleteitem() { // Delete the item that the user chose. varselectListBox = document.getElementById("selectlistbox"); varselectedListTitle = selectListBox.value; varselectedList = web.get_lists().getByTitle(selectedListTitle); varselectItemBox = document.getElementById("selectitembox"); varselectedItemID = selectItemBox.value; varselectedItem = selectedList.getItemById(selectedItemID); selectedItem.deleteObject(); selectedList.update(); context.load(selectedList); context.executeQueryAsync(onDeleteItemSuccess, onDeleteItemFail); } functiononDeleteItemSuccess() { // Refresh the list of items. getitems(); } functiononDeleteItemFail(sender, args) { // The item couldn’t be deleted – display an error message. alert('Failed to delete the item. ' +args.get_message()); } functiongetitems() { // Using a CAML query, get the items in the list that the user chose, and // set the context to the collection of list items. varselectListBox = document.getElementById("selectlistbox"); varselectedList = selectListBox.value; varselectedListTitle = web.get_lists().getByTitle(selectedList); varcamlQuery = newSP.CamlQuery(); camlQuery.set_viewXml("<View><ViewFields>" + "<FieldRef Name='ID' />" + "<FieldRef Name='Title' />" + "</ViewFields></View>')"); listItemCollection = selectedListTitle.getItems(camlQuery); context.load(listItemCollection, "Include(Title, ID)"); context.executeQueryAsync(onGetItemsSuccess, onGetItemsFail); }
  • 10. functiononGetItemsSuccess(sender, args) { // The list items were retrieved. // Show all child nodes. varlistItemEnumerator = listItemCollection.getEnumerator(); varselectItemBox = document.getElementById("selectitembox"); if (selectItemBox.hasChildNodes()) { while (selectItemBox.childNodes.length>= 1) { selectItemBox.removeChild(selectItemBox.firstChild); } } while (listItemEnumerator.moveNext()) { varselectOption = document.createElement("option"); selectOption.value = listItemEnumerator.get_current().get_item('ID'); selectOption.innerHTML = listItemEnumerator.get_current().get_item('Title'); selectItemBox.appendChild(selectOption); } } functiononGetItemsFail(sender, args) { // The list items couldn’t be retrieved - display an error message. alert('Failed to get items. Error: ' + args.get_message()); } })(); When you run the project it will upload the new app package to your SharePoint online developer hosted web and open up App Web page
  • 11. Now here we will create a new list say name it as “Contacts” and then click on create list
  • 12. Now let’s add a new item to the list Contacts, in the JavaScript code shown above there we are adding item to the Title field only. Similarly we can delete the item from the list, select the item from the drop and click on Delete Selected item Update? To read the data from list in the hosting web from app web: 'use strict'; varhostweburl; varappweburl; varclientContext; $(document).ready(function () { hostweburl = decodeURIComponent( getQueryStringParameter("SPHostUrl")); appweburl = decodeURIComponent( getQueryStringParameter('SPAppWebUrl') );
  • 13. alert(hostweburl); alert(appweburl); varscriptbase = hostweburl + '/_layouts/15/'; $.getScript(scriptbase+'SP.Runtime.js',function(){ $.getScript(scriptbase + 'SP.js', function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', createHostWebURLofAPP); } );}); }); functioncreateHostWebURLofAPP() { var factory; varappContextSite; varcollList; clientContext= newSP.ClientContext(appweburl); factory = newSP.ProxyWebRequestExecutorFactory(appweburl); clientContext.set_webRequestExecutorFactory(factory); appContextSite = newSP.AppContextSite(clientContext, hostweburl); this.web = appContextSite.get_web(); collList = this.web.get_lists(); clientContext.load(this.web); clientContext.load(collList); // // alert(hostweburl); // clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed); clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed)); functiononQuerySucceeded() { varlistInfo = ''; varlistEnumerator = collList.getEnumerator(); while (listEnumerator.moveNext()) { varoList = listEnumerator.get_current(); listInfo += '<li>' + oList.get_title() + '</li>'; } alert('Title: ' + this.web.get_title() + ' Description: ' + this.web.get_description()); }
  • 14. functiononQueryFailed(sender, args) { alert('Request failed. ' +args.get_message() + 'n' + args.get_stackTrace()); } } functiongetQueryStringParameter(paramToRetrieve) { varparams = document.URL.split("?")[1].split("&"); varstrParams = ""; for (vari = 0; i<params.length; i = i + 1) { varsingleParam = params[i].split("="); if (singleParam[0] == paramToRetrieve) returnsingleParam[1]; } }