Delete List Item Collection using ECMA Script

Leave a Comment
Hello All,

In a following post , we will see a code which will delete List Item Collection from SharePoint List using ECMA Script .
this example is used in a scenario like after completion of deletion of list Items , I need to insert some values in another list,for this generally we can write insert Code in Success Method of Delete.But in this example we are going to see some different approach. Not exactly callback but will act same as callback.

DeleteDetails(ItemID, function (isDetailsDeleted) {
                if (isDetailsDeleted) {
                    InsertToDetailsList(ItemID);
                }
            });

here, DeleteDetails is my function which will delete items from SPList. 

    var DeleteDetails = function (ItemID, OnComplete) {
    var isDetailsDeleted = false;
    var myArray = [];
    var context = SP.ClientContext.get_current();
    var parentContext = new SP.AppContextSite(context, SPHostUrl);
    var web = parentContext.get_web();
    var camlQuery = new SP.CamlQuery;
    var query = "<View> " +
            "<Query> " +
             "  <Where><Eq><FieldRef Name='ColumnName' /><Value Type='Number'>" + ItemID + "</Value></Eq></Where> " +
            "</Query> " +
            "</View>";
    camlQuery.set_viewXml(query);
    var list = web.get_lists().getByTitle("ListName");
    var listDetails = list.getItems(camlQuery);
    context.load(listDetails);
    context.executeQueryAsync(onQuerySucceeded, onQueryFailed);

    function onQuerySucceeded() {
        var listEnumerator = listDetails.getEnumerator();
        var itemCount = listEnumerator.$2K_0;

        while (listEnumerator.moveNext()) {
            var listItem = listEnumerator.get_current();
            myArray.push(listItem.get_id());
        }
        context.executeQueryAsync(onQueryDeleteSucceeded, onQueryFailed);
    }
    function onQueryDeleteSucceeded() {
        jQuery.each(myArray, function (i, val) {
            var newDelItem = list.getItemById(val);
            newDelItem.deleteObject();
        });
        context.executeQueryAsync(onDeleted, onQueryFailed);
    }
    function onDeleted() {
        isDetailsDeleted = true;
        OnComplete(isDetailsDeleted);
    }
    function onQueryFailed(sender, args) {
        isDetailsDeleted = false;
        alert('Delete Details failed. ' + args.get_message() +
                '\n' + args.get_stackTrace());
        OnComplete(isDetailsDeleted);
    }
    return isDetailsDeleted;
}

Note: the below code is executed in SP Hosted App,So you will see some Hosting Urls, Please change code as per your requirement.

Thanks,

Related Post

0 comments:

Post a Comment