Pages

Wednesday, March 1, 2017

Basic operations in Host Web from Add-in Web using PnP JavaScript Core Library

Introduction

My my previous blogposts I discussed on

  1. Use sp-pnp-js with SharePoint hosted Add-in
  2. Communicate with Host Web from Add-in Web through PnP JavaScript Core Library

This post will be a continue of the above two posts. In this post we will be addressing the basic operations on SharePoint list items.

Permission

In order to do operations on the list on host web we need to give permission to the List. In our case we have to set the permission “Scope” to “List” and “Permission” as “Manage”. Please refer the image below.

Click on AppManifest.xml –> Permission

Set “Scope” to “List” and “Permission” to “Manage”

image_thumb[1]

The addinWeb will be the Add-in web url and the hostWeb will be the Host Web url. You may download the solution from the link given at the bottom and refer for more.


Add new Item to List

  
    $pnp.sp.crossDomainWeb(addinWeb, hostWeb).lists.getByTitle("List1").items.add({
        Title: "Title"
    }).then(function (result) {
        alert("Item Added");
        //"result" will return couple of properties of newly created item. We can make use of them here
        console.log(result.data);
        console.log(result.data.Id);
    }).catch(function (err) {
        alert(err);
    });


Update existing Item

  
    //Get the item By Id and call the update
    $pnp.sp.crossDomainWeb(addinWeb, hostWeb).lists.getByTitle("List1").items.getById(2).update({
        Title: "Title Update"
    }).then(function (result) {
        alert("Item Updated");
        $("#message").html("Item Updated");
        //"result" will return couple of properties of updated item.
        console.log(result.data);
        console.log(result.data.Id);
    }).catch(function (err) {
        alert(err);
    });


Delete a exiting Item

  
 //Get the item By Id and call delete
    $pnp.sp.crossDomainWeb(addinWeb, hostWeb).lists.getByTitle("List1").items.getById(2).delete().then(function (result) {
        alert("Item Deleted");
        $("#message").html("Item Updated");
    }).catch(function (err) {
        alert(err);
    });

Using the above code snippet you can do the basic operations.

Conclusion

Hit F5 and you will prompt to Trust and select the List you want  give the permission to.

Select the List name from the dropdown and Click on “Trust”.


image_thumb[3]

You can download the code from the below.

https://drive.google.com/file/d/0ByEnOE8DAdvhSUhHWEJuTzBTUm8/view?usp=sharing

Reference

https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Items


No comments:

Post a Comment