Create a Custom Delete Button on SharePoint List Form using ECMAScript and Client Object Model

Create a Custom Delete Button on SharePoint List Form using ECMAScript and Client Object Model

On a SharePoint 2010 List Form (e.g Edit Form or Display Form), there is a ‘Delete Item’ button on the top Ribbon bar which can be used to delete the current list item.

image

When the list item has been deleted, the users would be redirected to the default view page of the list. However, sometimes, users want to be redirected to another custom page instead of the default view page when they delete the item using the ‘Delete Item’ Ribbon button. Also, they may want some business logics to be executed after the item has been deleted.

We can develop a custom Event Handler to redirect the page and add the required business logic. However, Event Handlers may not be suitable or practical for same cases. For example, post-delete event (e.g. ItemDeleted) is an asynchronous event in sharepoint while page redirection need happen in a synchronous process(i.e. item deletion and page redirection need happen in a same thread).

An alternative approach to solve this problem is to replace the ‘Delete Item’ button on the Ribbon bar with a copied/fake ‘Delete Item’ button and then use ECMAScript and Sharepoint Client Object Model to remove the item and implement business logics/page redirection on the post-delete event.

Below is the list of steps to create the custom delete button.

Step 1: Launch SPD and locate the target list. Create a custom List Form (e.g. Edit Form) for this list.

image

Step 2: Open the created list form, change it to ‘Code’ view and switch it to ‘Advanced Mode’. You will add the javascript code mentioned in the rest of post to the list form. You can find the full source code at bottom of this post.

image

Step 3: Make a copy of the ’Delete Item’ button and then hide the original button. We can do that using a JQuery-based approach which was original suggested by Charlie Chen.

//Get the original 'Delete Item' button object
var button = document.getElementById("Ribbon.ListForm.Edit.Actions.DeleteItem-Large");
if (button != null) {
    var $button = $(button);
    var html = $button.html();

    //Make a cope of the orginal 'Delete Item' button and then hide the orginal button
    $button.after("<a class="ms-cui-ctl-large">" + html + "</a>").hide().next().click(function (e) {

        //TODO Remove the List Item using Client Object Model

    });
}

Step 4: Delete the list item using ECMAScript and Client Object Model.

//Create current client context
var context = new SP.ClientContext.get_current();
//Get current web object
var web = context.get_web();
//Get the list where you want to delete item from
var list = web.get_lists().getByTitle('List Title');
//Get the item to delete
var itemToDelete = list.getItemById(itemID);
//execute delete command asynchronously
itemToDelete.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Failed));

Step 5: Implement the Success and Failed callback functions. The Success function would be triggered if the  context.executeQueryAsync (see the code segment above) commend has been executed successfully, the Failed function would be triggered if the command has failed.

function Success() {

    //TODO: Add Post-Delete Logic Here
}

function Failed(sender, args) {
    alert('Failed to delete the item.');
}

Step 6: Add the following line of code to load the script on the list form page onLoad event.

//Load the script
_spBodyOnLoadFunctionNames.push("addCustomDeleteButton");

Below is the completed source code used in the post.

//Load the script
_spBodyOnLoadFunctionNames.push("addCustomDeleteButton");</pre>
function addCustomDeleteButton() {

    //Get the original 'Delete Item' button object
    var button = document.getElementById("Ribbon.ListForm.Edit.Actions.DeleteItem-Large");

    if (button != null) {
        var $button = $(button);
        var html = $button.html();
        dialog = this;

        //Make a cope of the orginal 'Delete Item' button and then hide the orginal button
        $button.after("<a class="ms-cui-ctl-large">" + html + "</a>").hide().next().click(function (e) {

            //get the id of current item
            itemID = getQuerystring('ID')

            //remove the item using Sharepoint Client Object Model
            deleteItem(itemID)

            //unbind the click event handler
            var $this = $(this);
            $this.unbind("click");
            dialog = null;
        });
    }

}

function deleteItem(itemID) {

    //Create current client context
    var context = new SP.ClientContext.get_current();
    //Get current web object
    var web = context.get_web();
    //Get the list where you want to delete item from
    var list = web.get_lists().getByTitle('List Title');
    //Get the item to delete
    var itemToDelete = list.getItemById(itemID);
    //execute delete command asynchronously
    itemToDelete.deleteObject();
    context.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Failed));
}

function Success() {

    //TODO: Add Post-Delete Logic Here
}

function Failed(sender, args) {
    alert('Failed to delete the item.');
}

function getQuerystring(key, default_)
{
   if (default_==null) default_="";
   key = key.replace(/[\[]/,"<a>\\\[").replace(/[\]]/,"\\\</a>]");
   var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
   var qs = regex.exec(window.location.href);
   if(qs == null)
     return default_;
   else
     return qs[1];
}

Advertisements

2 thoughts on “Create a Custom Delete Button on SharePoint List Form using ECMAScript and Client Object Model

  1. I have used the function “deleteItem” in Emptyelement.xml for my custom ribbon’s custom delete button.

    but it is not working and not giving any error. what could be the mistake.
    is deleteObject not working for me? if so why?

    can you please help me out

    Thanks in advance

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s