Introduction
In this blog, we will learn how we can create items in a folder of the SharePoint list.
Follow the below steps to create an item in the folder.
Steps
Step 1
First, we will create JSON for the data parameter of POST call as below,
var itemProperties = {
'Title': 'Test item inside folder',
//server relative path
'Path': '/sites/{site collection name}/Lists/Projects/Internal'
};
- Here path will be the server relative path of the list folder in which we want to create an item.
- In the above JSON, the list name is Projects and there is one folder created with the name Internal.
Step 2
We will also define 2 other variables for site URL and list name.
var webUrl = this.props.context.pageContext.web.absoluteUrl;
var listName = "Projects";
Here I have created a property for context and assign value to context property as below,
const element: React.ReactElement < IManageListItemsProps > = React.createElement(ManageListItems, {
description: this.properties.description,
context: this.context
});
Step 3
Now we will create a URL for API as below,
var apiUrl = webUrl + "/_vti_bin/listdata.svc/" + listName;
Step 4
Now we will create a separate method to create an item, so we can also reuse it,
public insertdata(apiUrl: string, requestdata, requestDigest): Promise < number > {
var url = apiUrl;
return new Promise < number > ((resolve, reject) => {
try {
fetch(url, {
method: "POST",
credentials: 'same-origin',
headers: {
Accept: 'application/json',
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": requestDigest
},
body: requestdata
}).then((response) => {
alert("Item Created");
}).catch((error) => {
reject(error);
});
} catch (e) {
console.log(e);
reject(e);
}
});
}
Step 5
As we are doing the POST call to create an item, we need a request digest. So, we will get a request digest from context as below.
We will import libraries to get the request digest as below,
import { IDigestCache, DigestCache } from '@microsoft/sp-http';
Then we can get the request digest and use it in our POST call to create an item,
const digestCache: IDigestCache = this.props.context.serviceScope.consume(DigestCache.serviceKey);
digestCache.fetchDigest(this.props.context.pageContext.web.serverRelativeUrl).then(async (digest: string): Promise < void > => {
await this.insertdata(apiUrl, JSON.stringify(itemProperties), digest);
});
In the above code, we can see, after getting the value of the request digest we have to call our method to create the item. So we will call this method as below,
await this.insertdata(apiUrl, JSON.stringify(itemProperties), digest);
Conclusion
This is how we can create items in a folder of the SharePoint list. Hope this blog will be helpful!