SharePoint Tips

Saturday, June 23, 2018

SharePoint hosted Add-In : Read list data : JSOM


In last post (Step by step guide to create “SharePointHosted Add-In” in SharePoint Online (Office 365)), I created a basic SharePoint hosted Add-In as shown below.


Now, I’ll add logic to this Add-In to read data from a SharePoint list (VendorList) as shown below.


Step 1- Open Default.aspx file and add new div as shown below.


Step 2- Open App.js file. Replace code in js file with code given below.


Changes in App.js file
var Items = null;
'use strict';
var listItems;
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', ListItems)
});

function ListItems() {
    var context = new SP.ClientContext(appweburl);
    var ContextSite = new SP.AppContextSite(context, hostweburl);
    var web = ContextSite.get_web();
    context.load(web);
    var list = web.get_lists().getByTitle('VendorList');
    var caml = new SP.CamlQuery();
    caml.set_viewXml("<View><Query></Query></View>"); // U can change the query for getting desired result  
    Items = list.getItems(caml);
    context.load(Items);
    context.executeQueryAsync(onSucceededCallback, onFailedCallback);
}

function onSucceededCallback(sender, args) {
    var enumerator = Items.getEnumerator();
    var myText = 'Items in VendorList: <br><br>';
    while (enumerator.moveNext()) {
        var listItem = enumerator.get_current();
        myText += 'Title: ' + listItem.get_item('Title') + '<br>';
        myText += 'Address: ' + listItem.get_item('Address') + '<br><br>';
    }
    myDiv.innerHTML = myText;
}

function onFailedCallback(sender, args) {
    var myText = '<p>The request failed: <br>';
    myText += 'Message: ' + args.get_message() + '<br>';
    myDiv.innerHTML = myText;
}

function getQueryStringParameter(paramToRetrieve) {
    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];
    }
}

Step 3 – Deploy your Add-In after all changes.


Step 4- You may get below error as your Add-In don’t have enough permissions.


Step 5- For simplicity we are providing Full Control at Site Collection level. You can also provide only Read access.


Step 6- Now deploy Add-In again and you’ll get below screen.


Step 7- Trust Add-In by clicking ‘Trust It’ button.

Here is the Add-In with data from VendorList


No comments:

Post a Comment