Reputation: 107
I have a requirement where I need to update the list item if it is already exist and create a new one if the item doesn't exist. Everything I need to manage from single method as I am taking data from custom form to update item. Is there any way to do this in sharepoint online rest api? I am using below method to do update item
public static UpdateSaveSectionC(formData: any,id:any): PromiseLike<string> {
// Return a promise
const siteURL= "https://abc.sharepoint.com/sites/process";
return new Promise((resolve, reject) => {
for (var i = 0; i < formData.Category.length; i++) {
const restUrl = siteURL + `/_api/web/lists/getbytitle('List')/items(${id[i]})`;
const headers = { 'accept': 'application/json;odata=verbose', 'content-Type': 'application/json;odata=verbose','X-HTTP-Method': 'MERGE','IF-MATCH': '*'};
const listTitle = "List";
const data = {
'__metadata': { 'type': 'SP.Data.' + listTitle + 'ListItem','results':[] },
Category: formData.Category[i],
Recommendationsuggestion: formData.Recommendationsuggestion[i],
}
Helper.executeJson(restUrl, "POST", headers, JSON.stringify($.extend(true,{}, data)))
.then((response) => {
// Resolve the request
resolve("success");
}).catch( (e) => {
if(e.responseJSON.error.message.value.indexOf("The request ETag value") != -1)
{
resolve("Please refresh the page, and resubmit your changes");
}
});
}
`
Upvotes: 0
Views: 2025
Reputation: 1846
As @joyBlanks said, OOTB there is no such UpdateOrInsert functionality in Sharepoint API. But Using SPOHelper Utility You can minimize code to achieve functionality. SPOHelper is lightweight REST Utility for Sharepoint Online.
var reqUrl="https://tenant.sharepoint.com/sites/ABCSite/_api/Lists/getbytitle('SPO List')/items";
var id=2;
var formdata={Title :"POST test update",Number:1234};
if(id){
var tempReqUrl=`${reqUrl}(${id})`
var result= await SPUpdate({url:tempReqUrl,payload:formdata})
// If request fails
if(result && result.ok){
console.log("Request Success with Update",result)
}else{
result =await SPPost({url:reqUrl,payload:formdata});
console.log("Request Success with Insert",result)
}
}
Upvotes: 0
Reputation: 1252
This is additive to @Lee_MSFT's post so please read his post first.
The way you're querying can be simplified also. I recommend you use either jQuery promises or PNP.js as it'll make your life easier. jQuery example:
function getItem(name) {
var query = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('list title')/items?$filter=UniqueField eq " +name;
return $.ajax({
url: query,
method: "GET",
headers: {
Accept: "application/json;odata=verbose"
}
});
}
getItem("hi.docx").done(function (result) { if(!result){uploadFile()}};
PNP.js is the better option IMO if it's possible for you to look into.
Upvotes: 0
Reputation: 5493
Using rest api to filter list to confirm the item not exist based on unique key,
/_api/web/lists/getbytitle('list title')/items?$filter=UniqueField eq 'value'
Based on returned items count to know the result.
Upvotes: 1
Reputation: 6527
There is no Upsert mode in Sharepoint rest api for lists.
Option1: The recommended approach would be while in the form user is filling up data give an auto suggestion based on the entries filled up. So at the time of submit you will know that the item in question has an id
or not so to insert or to update.
Option2: in your submit method you can quickly look up an item if exists or not chain it to update or insert method
Note insert and update have 2 different end points all together.
Upvotes: 0