Pnp Guide - JackHu88/Comm GitHub Wiki
<script type="text/javascript" src="../SiteAssets/js/fetch.js"></script>
<script type="text/javascript" src="../SiteAssets/js/es6-promise.min.js"></script>
<script type="text/javascript" src="../SiteAssets/js/pnp.min.js"></script>
<script type="text/javascript">
$pnp.setup({
headers: {
"Accept": "application/json; odata=verbose"
}
});
//On promise
$pnp.sp.web=new $pnp.Web(_spPageContextInfo.webServerRelativeUrl);
</script>
<script type="text/javascript">
$pnp.sp.web.get().then(function (web) {
var currentWeb = web;
});
$pnp.sp.web.ensureUser("[email protected]").then(function (user)
{
var u = user;
var userId= user.data.Id;
});
$pnp.sp.web.getUserById(1).get().then(function(user){
console.log(user)
});
var batch = $pnp.sp.createBatch();
$pnp.sp.web.inBatch(batch).ensureUser("a6anqzz").then(function (user){
var userId= user.data.Id;
console.log(userId);
})
batch.execute().then(d => console.log("Done"));
//$pnp.sp.web.select("AllProperties").expand("AllProperties")
$pnp.sp.web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
console.log(r);
});
/*** new item ***/
$pnp.sp.web.lists.getByTitle("TestList").items
.add({"Title":"Test01","UserId":"10"})
.then(function(result){
console.log(result.data)
})
var sample=document.getElementById("sample");
function ensureSampleData() {
return new Promise(function (resolve, reject) {
$pnp.sp.web.lists.ensure("Read List Sample").then(function (result) {
if (result.created) {
Promise.all([
result.list.items.add({ Title: "Item 1" }),
result.list.items.add({ Title: "Item 2" }),
result.list.items.add({ Title: "Item 3" }),
result.list.items.add({ Title: "Item 4" }),
result.list.items.add({ Title: "Item 5" }),
result.list.items.add({ Title: "Item 6" }),
]).then(function () { resolve(result.list); });
} else {
resolve(result.list);
}
});
});
}
// ensure our list and data, then retrieve it:
ensureSampleData().then(function (list) {
// get the first page of items
list.items.top(2).orderBy("Title").getPaged().then(function (result) {
// show the first page of results
sample.append(result.results);
// always see if there are more results before requesting them
if (result.hasNext) {
result.getNext().then(function (result2) {
// show the second page of results
sample.append(result2.results);
});
}
});
});
/*** update item ***/
$pnp.sp.web.lists.getByTitle("TestList").items.getById("6").update({"Title":"test01"}).then(function(result){
console.log(result.item);
})
$pnp.sp.web.lists.getByTitle("Marketing").items.getById("5").update({"UserId":{"results": [59,42] }}).then(function(result){
console.log(result);
})
$pnp.sp.web.lists.getByTitle("TestList").items.top(1).filter("Title eq 'test01'")
.get($pnp.ODataEntityArray($pnp.Item)).then(function(items){
console.log(items);
if (items.length > 0) {
items[0].update({
Title: "updated",
}).then(_ => {
console.log("Update Complete of item index 0.")
});
}
});
/*** query list ***/
$pnp.sp.web.lists.getByTitle("TestList").getItemsByCAMLQuery().then(function (listitems) {
console.log(listitems);
});
var camlQuery={
ViewXml: "<View>\
<RowLimit>0</RowLimit>\
<Query>\
<Where>\
<Eq><FieldRef Name='User' /><Value Type='User'><UserID/></Value></Eq>\
</Where>\
</Query>\
</View>"
};
$pnp.sp.web.lists.getByTitle("TestList").getItemsByCAMLQuery(camlQuery).then(function (listitems) {
console.log(listitems);
});
//expand user field
$pnp.sp.web.lists.getByTitle("TestList").items.filter("Title eq 'Test'")
.expand('Author').select("Id,Author/Title,Author/EMail").get().then(function(result) {
console.log(result)
});
//filter current user
$pnp.sp.web.lists.getByTitle('TestList').items.filter("AuthorId eq '"+_spPageContextInfo.userId+"'").get().then(function(result) {
console.log(result)
});
$pnp.sp.web.lists.getByTitle("TestList").items.filter("Title eq 'Test'").get().then(function(result) {
console.log(result)
});
$pnp.sp.web.lists.getByTitle('TestList').items.skip(5).top(10).get().then(function(d) {
console.log(d.map(function(d) {
return d.Id;
}));
});
// we can also select and order results
$pnp.sp.web.lists.getByTitle('TestList').items.select("Title").orderBy("Title").get().then(function(result) {
console.log(result)
});
// we can also filter results
$pnp.sp.web.lists.getByTitle('TestList').items.select("Title").filter("Title eq 'Item 1'").get().then(function(result) {
console.log(result)
});
/**** create folder ****/
$pnp.sp.web.getFolderByServerRelativeUrl("/sites/dev/Shared Documents").folders.add("test").then(function(result){
console.log(result.data.ServerRelativeUrl);
})
$pnp.sp.web.getFolderByServerRelativeUrl("/sites/dev/Shared Documents").folders.add("test").then(function(result){
var file=$("#Attachment").get(0).files[0];
result.folder.files.add(file.name,file,true);
})
/*** get user by id ***/
$pnp.sp.web.siteUsers.getById("10").get().then(function(result) {
console.log(result);
});
//$pnp.sp.web.siteUsers.getByLoginName("'<User Login Name>'")
//$pnp.sp.web.siteUsers.getByEmail("<User Email ID>")
/*** check user in group ***/
$pnp.sp.web.siteGroups.getByName('Dev Owners').users
.getById("10").get().then(function(result){
console.log(result);
}).catch(function(err) {
console.log("User not found: " + err);
});
//add user to group
$pnp.sp.web.siteGroups.getByName("Dev Owners").users.add("i:0#.f|membership|[email protected]").then(function (d) {
d.select("Id,Email,LoginName,Title").get().then(userData => {
console.log(userData);
});
});
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(780)/users";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({
'__metadata': { 'type': 'SP.User' },
'LoginName': 'i:0#.f|membership|[email protected]'
}),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: function(){
console.log("done")
},
error: function(err){
console.log(err)
}
});
var batch = $pnp.sp.createBatch();
$pnp.sp.web.siteGroups.getByName("Dev Members").users
.inBatch(batch).add("i:0#.f|membership|[email protected]").then(function(d){
console.log(d)
});
$pnp.sp.web.siteGroups.getByName("Dev Members").users
.inBatch(batch).add("i:0#.f|membership|[email protected]").then(function(d){
console.log(d)
});
$pnp.sp.web.siteGroups.getByName("Dev Members").users
.inBatch(batch).add("i:0#.f|membership|[email protected]").then(function(d){
console.log(d)
});
batch.execute().then(function(){
console.log("batch done");
});
//Retrieve Properties of Current User
$pnp.sp.profiles.myProperties.get().then(function(result) {
props = result.UserProfileProperties.results;
var propValue = "";
props.forEach(function(prop) {
propValue += prop.Key + " - " + prop.Value + "<br/>";
});
document.getElementById("sample").innerHTML = propValue;
}).catch(function(err) {
console.log("Error: " + err);
});
//$pnp.sp.profiles.getPropertiesFor("i:0#.f|membership|[email protected]")
/***** batch *****/
var batch = $pnp.sp.createBatch();
var promises = [];
promises.push($pnp.sp.web.lists.getByTitle('Batch').items.inBatch(batch).add({Title:Date.now().toString()}))
promises.push($pnp.sp.web.lists.getByTitle('Batch').items.inBatch(batch).add({Title:Date.now().toString()}))
Promise.all(promises).then(function(){
console.log("Batch items creation is completed");
})
batch.execute();
var batchResults = [];
var batch = new $pnp.sp.createBatch();
$pnp.sp.web.getList('/sites/dev01/lists/custom01').items.inBatch(batch).get().then(function(d) {
batchResults.push({
custom01: d
});
});
$pnp.sp.web.getList('/sites/dev01/lists/custom02').items.inBatch(batch).get().then(function(d) {
batchResults.push({
custom02: d
});
});
for (var i = 0, len = 10; i < len; i += 1) {
$pnp.sp.web.getList('/sites/dev01/lists/custom03').inBatch(batch).items.add({
Title: 'Item ' + i
});
}
batch.execute().then(function() {
console.log("All is done!", batchResults);
});
/***** File ***/
$pnp.sp.web.getFolderByServerRelativeUrl("/sites/dev/SharedDocuments")
.files.add(file.name,file,true).then(function(results){
return results.file.listItemAllFields.get().then(function(item) {
return item.Id;
});
}).then(function(itemId) {
// set metadata
metadata={
"SampleNo": "1111"
};
if (metadata) {
return $pnp.sp.web.lists.getByTitle("Document Library").items.getById(itemId).update(metadata);
} else {
return Promise.resolve();
}
});
//remove files
var promises = [];
for(filePath in existingFiles){
promises.push($pnp.sp.web.getFileByServerRelativeUrl(filePath).delete());
}
Promise.all(promises).then(function () {
console.log("Done");
})
//expand folder & files
$pnp.sp.web
.getFolderByServerRelativeUrl(_spPageContextInfo.webServerRelativeUrl + '/Documents') // Here comes a folder/subfolder path
.expand("Folders,Files").get().then(function (result) {
console.log(result);
});
//$pnp.sp.web.getFileByServerRelativeUrl(file.url)
var files;
$pnp.sp.web
.getFolderByServerRelativeUrl(_spPageContextInfo.webServerRelativeUrl + '/Pages') // Here comes a folder/subfolder path
.files
.expand('Files/ListItemAllFields') // For Metadata extraction
.select('Title,Name') // Fields to retrieve
.get()
.then(function(item) {
files = item;
});
var folders;
$pnp.sp.web
.getFolderByServerRelativeUrl(_spPageContextInfo.webServerRelativeUrl + '/Pages') // Here comes a folder/subfolder path
.files
.expand('Folders/ListItemAllFields') // For Metadata extraction
.select('Title,Name') // Fields to retrieve
.get()
.then(function(item) {
folders = item;
});
//
//get columns from folder
$pnp.sp.web
.getFolderByServerRelativeUrl('/sites/dev/SharedDocuments')
.files
.expand('ListItemAllFields')
.get()
.then(function (files) {
var results = files.filter(file => {
return file.ListItemAllFields;
});
console.log(results);
});
let batch = pnp.sp.createBatch();
$pnp.sp.web.getFolderByServerRelativeUrl(folderName).folders.inbatch(batch).add(folder1RelatedServerUrl).then(r => {
console.log(r)
});
$pnp.sp.web.getFolderByServerRelativeUrl(folderName).folders.inbatch(batch).add(folder2RelatedServerUrl).then(r => {
console.log(r)
});
$pnp.sp.web.getFolderByServerRelativeUrl(folderName).folders.inbatch(batch).add(folder3RelatedServerUrl).then(r => {
console.log(r)
});
batch.execute().then(() => console.log("All done!"));
//.orderBy("Modified", true)
//move file
$pnp.sp.web.getFileByServerRelativeUrl(serverRelativeUrl).moveTo(finalPath, 1).then(r => {
console.log(r)
});
//paging
$pnp.sp.web.lists.getByTitle("Config3").items.orderBy("Title").top(2).getPaged().then(d => {
show(d);
d.getNext().then(d => show(d));
});
//add multiple items
var list = $pnp.sp.web.lists.getByTitle("BatchTest");
list.getListItemEntityTypeFullName().then(entityTypeFullName => {
var batch = $pnp.sp.web.createBatch();
for (var i = 0; i < 100; i++) {
list.items.inBatch(batch).add({
Title: "Test"+i,
}, entityTypeFullName).then(b => {
console.log(b.data.Title);
});
}
batch.execute().then(d => console.log("Done"));
//send email
var emailProps = {
To: to,
CC: cc,
BCC:[],
Subject: subject,
Body: body
};
$pnp.sp.utility.sendEmail(emailProps ).then(function() {
console.log("Email Sent");
});
//search user by name
$pnp.sp.utility.searchPrincipals(
"Jack Hu",
$pnp.PrincipalType.User,
$pnp.PrincipalSource.All,
"",
10).then(function(principals){
console.log(principals.SearchPrincipalsUsingContextWeb.results);
});
//expand user in group
$pnp.sp.utility.expandGroupsToPrincipals(["Dev Owners"]).then(function(principals){
console.log(principals.ExpandGroupsToPrincipals.results);
});
//
$pnp.sp.web.lists.getByTitle("Config3").items.filter("substringof('"+name+"',Title)").get().then(function(d){}
console.log(d);
});
$pnp.sp.web.lists.getByTitle("Config3").items.filter("startswith(Title,'"+name+"')").get().then(function(d){}
console.log(d);
});
//get user groups
$pnp.sp.web.getUserById(1).groups.get().then(function(data){console.log(data)})
//get all item over 5000+
$pnp.sp.web.lists.getByTitle("List").items.select("Title").getAll().then(function (data2) {
console.log(data2);
})
//
$pnp.sp.web.lists.getByTitle("Config3").items.filter("substringof('"+name+"',Title)").get().then(function(d){}
console.log(d);
});
$pnp.sp.web.lists.getByTitle("Config3").items.filter("startswith(Title,'"+name+"')").get().then(function(d){}
console.log(d);
});
//file copy
$pnp.sp.web.getFolderByServerRelativeUrl("/sites/GCCN/rnd/tourrequest/documents/folder1").files.getByName("file.txt")
.copyto(strnewurl='/sites/GCCN/rnd/tourrequest/documents/folder2/acento.txt',boverwrite=true);
//get all
$pnp.sp.web.lists.getByTitle("ClassHistory").items.select("Id,CourseNo").getAll().then(function (data2) {
console.log(data2);
})
});
substring(triggerBody()?['TestingReport'],add(lastIndexOf(triggerBody()?['TestingReport'],'/'),1),length(triggerBody()?['TestingReport']))
//Upload Multiple File Attachment
https://www.c-sharpcorner.com/article/upload-mul-file-attachment-into-sharepoint-list-using-pnp-js/
//Upload multiple files to SP document library
https://github.com/pnp/pnpjs/issues/1248
</script>
https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Items#add-multiple-items
https://pnp.github.io/pnpjs/sp/items/
https://cdnjs.com/libraries/pnp-pnpjs
If you are developing in SPFx and install and import the PnPjs libraries the default behavior will be to bundle the library into your solution. You have a couple of choices on how best to work with CDNs and SPFx. Because SPFx doesn't currently respect peer dependencies it is easier to reference the pnpjs rollup package for your project. In this case you would install the package, reference it in your code, and update your config.js file externals as follows:
Install
npm install @pnp/pnpjs --save
In Code
import { sp } from "@pnp/pnpjs";
sp.web.lists.getByTitle("BigList").get().then(r => {
this.domElement.innerHTML += r.Title;
});
config.js
"externals": {
"@pnp/pnpjs": {
"path": "https://cdnjs.cloudflare.com/ajax/libs/pnp-pnpjs/1.1.4/pnpjs.es5.umd.bundle.min.js",
"globalName": "pnp"
}
}
https://github.com/pnp/pnpjs/blob/ae7ee2db75b044c6751403ee835a849e563cb9b1/packages/documentation/deployment.md
https://pnp.github.io/pnpjs/transition-guide/
https://github.com/pnp/pnpjs/tree/version-2/samples/custom-bundle-webpack
https://webpack.js.org/configuration/
import { SPComponentLoader } from '@microsoft/sp-loader';
let cssURL = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";
SPComponentLoader.loadCss(cssURL);
SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js', { globalExportsName: 'jQuery'});
"externals": {
"jquery": {
"path": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"globalName": "jQuery"
},
"SPServices": {
"path": "https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices-2014.02.js",
"globalName": "jQuery",
"globalDependencies": [ "jquery" ]
}
},
const $: any = require("jquery");
require('SPServices');
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Alerts",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
console.log(xData);
$(xData.responseXML).SPFilterNode("z:row").each(function() {
console.log($(this).attr("ows_Title"))
});
}
});
});
https://github.com/SharePoint/PnP-JS-Core/wiki/Using-sp-pnp-js-in-SharePoint-Framework
https://sharepains.com/2017/07/18/office-365-spfx-samples-a-complete-overview/