Tuesday, September 11, 2012

Use Javascript to Delete a List Item in SharePoint 2010

I recently was working on a sandboxed webpart that displayed some list items to the user in a modal window.  The user was shown a View, Edit, and Delete icon for each list item.  The View and Edit were pretty straight forward, I just crafted a url using the DefaultDisplayFormUrl and DefaultEditFormUrl respectively.  The Delete posed a little challenge for the following reasons:
  • Being a modal window, I did not want to perform a post back as this is just not best practice
  • This was a sandboxed solution with no jQuery in the overall environment, so I couldn't include it (CDN was not an option)
So that left me with Javascript and the SharePoint ECMAScript client object model.  Luckily this was pretty straight forward and worked like a charm.  Here is the code:

 <script  type="text/ecmascript"> 
     var  itemId;
     var  currentElement;
 

// Variable element could be removed, using it to hide the list item once its deleted
     function  deleteListItem(id, siteUrl, listName, element) {
         itemId = id;
         currentElement = element;
         var  clientContext = new  SP.ClientContext(siteUrl);
         var  oList = clientContext.get_web().get_lists().getByTitle(listName);
         var oListItem = oList.getItemById(id);
         oListItem.deleteObject();
         clientContext.executeQueryAsync(Function.createDelegate(this , this .onQuerySucceeded), Function.createDelegate(this , this .onQueryFailed));
     }
 

     function  onQuerySucceeded() {
// Variable element was in a table, this line hides the TR
         currentElement.parentNode.parentNode.style.display = 'none' ;
         alert('Item successfully deleted!' );
     }
 

     function  onQueryFailed(sender, args) {
         alert('Request failed.'  + args.get_message() + '  + args.get_stackTrace());
     }
 
 <script>
 

A couple of things to note here, as I did in the comments.  I was passing in a reference of the Delete icon element so I could hide it after the delete took place.  I was using a DataGrid control, so it rendered as a table.  I used the Javascript 'parentNode' method to work my way up to the TR in the table and hide the entire row.

Let's walk through what this code is doing:
  • First we declare two global variables to hold our itemID and element.  Oddly enough, I don't use these anywhere in the code!  However, they get set in the main function "deleteListItem" and could be used later, say in the confirmation.  The element variable does get used to hide the table row where the item was sitting.
  • deleteListItem function: This is the main function that does most of the work.  Let's step through it:
    • First we set the global variables, pretty easy!
    • Next we get a reference to the current client context passing in the siteUrl that was passed into the function.
    • Once we have a context, we can open the list using the listName that was passed in.
    • We get the list item by its ID (not the GUID), the ID was passed in as well, how convenient!
    • *We call deleteObject() on the list item to mark it for deletion.  This is key here, this does not delete the item, not yet.
    • Finally we call the ExecuteQueryAsync method on the clientContext object.  This is what finalizes the delete.  We also register our callback functions here.
  • onQuerySuceeded function: This function fires is the delete was a success.  We simply show an alert to the user here and remove the table row, as I don't want them to try to delete a second time.
  • onQueryFailed function: This function will fire if any error occurs.  Again, just simply showing an alert with information as to why the operation failed.
*From MSDN: "Communication with the server occurs when you call the ExecuteQuery method, or the ExecuteQueryAsync method, on the ClientContext instance.".  So above when we called "deleteObject()", it was simply marking that item for deletion, its the ExecuteQueryAsync which actually sends that request to the server for processing.

Here is the link that was built on the server which got rendered out:


(Sorry for the image!  My copy as HTML in Visual Studio did not like this code at all!)

This link was in a method that took the following parameters:
  • int itemId - The ID of the list item.  Not the GUID, the ID.
  • string siteServerRelativeUrl - This was the Web server relative Url, so it came from SPListItem.ParentList.ParentWeb.ServerRelativeUrl
  • string parentListTitle - The SPListItem's parent List title, which came from SPListItem.ParentList.Title
As you can see in the link I built, I created an onclick event that simply calls the "deleteListItem" function, passing in the information we need.

I also used a standard SharePoint image from the Layouts folder.  SharePoint uses either a sprite image to render all the buttons, or individual images from the layouts folder.  I found it easier to use the single image here.  You can always fire up FireBug and inspect a button to get the image you need.

And that's it for deleting a list item using Javascript.

Enjoy!

No comments:

Post a Comment