SharePoint 2013 ClientContext: how to delete specific list items using MULTIPLE CONDITION filter?

Using SP.ClientContext

from the end Javascript, below is the code I used to "UPDATE" a list item. Just:

    var clientContext = new SP.ClientContext( siteURL );
    spList = clientContext.get_web().get_lists().getByTitle( myListName );

    this.spList_ExistingItem = spList.getItemById( itemID );
    spList_ExistingItem.set_item( 'FullName', myFullName );
    spList_ExistingItem.set_item( 'Age', myAge );

    spList_ExistingItem.update();
    clientContext.executeQueryAsync(succeeded_handler, fail_handler);

      

This allows me to query for aupdate

list item using ONE condition, which is:getItemById(itemID)

here.

Now let's say that I want to remove any element that :

  • Age = 30
  • Country = USA

Then how can I make a query like this with multiple conditions . And then even to DELETE , please?


UPDATED


As per the answer below, I found the REST API to be simpler and cleaner to use for the Client / Javascript end as compared to CSOM. (So, of course, I've already changed all my codes to REST APIs.)

So, let's conclude that I suggest using the REST API, not CSOM (SP.ClientContext).

Thank!:)

+3


source to share


1 answer


This can be done in two different ways, either via CSOM / JSOM or via the SharePoint REST API. Since you are using the CSOM / JSOM model in your question, I will show you how it was done using this method.

Using CSOM / JSOM

To filter SP.ListItem

under mulitple conditions, there are no methods that take arguments as multiple filter fields. Instead, you have to resort to using a CAML query to specify the list items you want, as shown below.

var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );

//Create a CAML-query with your filter conditions
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Age\'/>' + 
    '<Value Type=\'Number\'>30</Value></Eq>
    <Eq><FieldRef Name=\'Country\'/>' + 
    '<Value Type=\'Text\'>US</Value></Eq></And></Where></Query><RowLimit>10</RowLimit></View>');

//The query will return a collection of items matching your conditions
this.collListItem = spList.getItems(camlQuery);

clientContext.load(collListItem);

//Execute the query
clientContext.executeQueryAsync(function () {

    var itemCount = collListItem.get_count();
    //For each list item in the collection, mark it to be deleted
    for (var i = itemCount - 1; i >= 0; i--) {
        var oListItem = collListItem.itemAt(i);
        oListItem.deleteObject();
    };

    //Execute the delete operation
    clientContext.executeQueryAsync(deleteSucceeded, deleteFailed);
}, fail_handler);

      

Using the SharePoint REST API

This method assumes that you are using jQuery to make simple simple calls $.ajax()

and that you are using the promise functionality as you may have multiple elements to remove. It also assumes that you understand how to use jquery deferred objects to run chains in sequence asynchronously.

The simple idea is



  • Make a request to the REST api and get all items matching your filter conditions.
  • For each collection object returned, create another query that will remove the item and add the query to the queries array
  • When all requests are met, do whatever you want!

Please note that you may need to modify the REST api call to match your columns. Just use your browser or postman to check if your request is correct.


function getItemsToDelete () {
    //You might have to modify this so it filters correctly on your columns
    var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + myListName + ")/items?$filter=Age eq 30 and Country eq 'US'")

    //Return and ajax request (promise)
    return $.ajax({
        url: requestUrl,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(result) {
            $.each(result.d.results, function(index, item){
                //Note that we push the ajax-request to the array
                //that has been declared a bit down
                itemsToDelete.push(deleteItem(item));
            });            
        },
        error: function(error) {
            //Something went wrong when retrieving the list items
        }
    });    
}

function deleteItem (item) {
    //All SP.ListItems holds metadata that can be accessed in the '__metadata' attribute
    var requestUrl = item.__metadata.uri;

    return $.ajax({
        url: requestUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": item.__metadata.etag,
            "X-HTTP-Method": "DELETE"
        },
        success: function() {
            console.log("Item with ID " + item.__metadata.id + " successfully deleted!");
        },
        error: function(error) {
            //Something went wrong when trying to delete the item
        }
    });    
}


//Declare an array of deferred objects that hold a delete request
//for each item that is to be deleted
var itemsToDelete = [];

//First get the items to delete
$.when(getItemsToDelete()).then(function () {
    $.when.apply($, itemsToDelete).then(function(){
        console.log("All items are deleted!");
    });
});

      


Some helpful sources

jQuery Deferred Object CRUD operations for list items with SharePoint REST api

+7


source







All Articles