My scenario is, I have a list called ChildList with parent item ID. In the child list, I have multiple items with parent ID. Now I want to delete multiple child items passing single ParentID. Like we do in SQL, "Delete from table where columnname=value". This will delete multiple rows having same column value. Can this be done REST API using JSOM/CSOM ?
1 Answer
REST API
Note: Expecting that PARENTLIST
'ID' field is a lookup field in CHILDLIST
with name 'PARENT'
Call the DeleteChildItems
function by passing the parentId
function DeleteChildItems(parentId)
{
getItems("/_api/Web/Lists/GetByTitle('CHILDLIST')/items?$filter=PARENT/ID eq "+parentId).done(function(data){
var noChildItems = data.d.results.length; //number of child items to be deleted
data.d.results.forEach(function(item){
var childId = item.ID;
deleteItem("/_api/Web/Lists/GetByTitle('CHILDLIST')/getItemById("+childId+")",item).done(function(d_data){
//deleted child item.
});
});
});
}
//Get items
function getItems(url){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
//Delete Item
function deleteItem(url, oldItem) {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "DELETE",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": oldItem.__metadata.etag
}
});
}