Delete All Items in a List – The « Ribbonnized Way »

Summary

This article describes how to create a new tab in the SharePoint ribbon that will be displayed on every list having a base type of “Generic List”. The ribbon extension will contain a button that will delete all items in a list by calling a Javascript that uses the SharePoint Client Object Model.

The Story

I’ve discussed this many times before, I’m a big believer in logging errors from custom SharePoint modules into custom lists. Given, this approach has a certain performance impact on the server, but the benefits you get out of it are worth taking the hit. You can run custom reports on the items, identify trends, be proactive by setting alerts, etc. However, where it really becomes a problem is when you don’t have a good strategy in place to decide how frequently items need to be deleted from the list. I’m sure all of you have experienced some frustration with the way SharePoint handles item deletion, only allowing you to delete the items display in the current view. If you have paging enabled, you may be looking at having to repeat the operation on several pages of items. Off course you can go and create a view that would display all items in the list, but that will often result in very slow operations, or in you exceeding the view throttling.

What we need is an easy way to go and delete all items in a list, something that would be as simple as pressing a button to make all items vanish. Off course we could go and code a nice visual web part, have it deployed at the farm level and then plug in on a page somewhere to do our biding. I’m not interested in that. That’s the easy and cheap way of doing it. No, what I want is something that would appear on all my lists, and would allow me to clean all items inside of it with a simple click on my mouse. What I need is a new ribbon extension!

The nice thing about Ribbon extensions is that they can easily be Sandboxed, meaning we can deploy them in the cloud, which is always a bonus. So let’s do that, create a new ribbon extension that will display a nice button allowing us to wipe any list clean of its items, and have it deployed onto our SharePoint Online Cloud, in my case Office 365. The content of this blog post was Demo #4 of my Techdays Canada session in both Toronto and Montreal in Fall of 2011.

The Logic Behind the Module

First off, let’s build the script that will allow us to achieve what we are looking for. Because the ribbon runs on the client’s side, we will develop the script using the ECMAScript SharePoint Client Object Model. Please don’t let the name scare you, it’s only Javascript. The script I built does the following, it starts off by getting the list currently selected, or in our case displayed on screen. It then queries the list using a CAML query that does the following, return every item that has an ID that is greater or equal to 1, which always returns all items. We then execute the Asynchronous query and jump onto the following method, which loops through all elements and adds their ID in a new array. We then loop through the array, and delete items from the list based on their IDs. The reason for this is that while looping inside of a collection, it is not permitted to alter its size, meaning that we cannot add or delete items when looping through the enumerator.

The second step is to register this script some places where it will be made accessible by all lists. To the Master Page! I’m lazy so I simply added the javascript to the end of the Master Page’s Head tag. As a best practice I would recommend you create a separate .js file and have it linked from your master page, but since we’re only demoing this, copying its content in the Master page directly will do.

The last but none the least step is to go and create our ribbon extension. The extension definition specifies a new tab that will have a single group of button, with a single row, having a single large button. The button will be set to us the out of the box Warning icon. Please make sure you point the icon to a file that will likely exist in every farm instance if your solution is aimed at the cloud. The button will call our newly developed javascript method and will be displayed on item of type ID = 100, which is the ID of type “Generic List” For a complete list of all possible type IDs we can use, please refer to the following Microsoft MSDN article: http://msdn.microsoft.com/en-us/library/ms415091.aspx .

How To

The following section gives the step by step approach one should follow to get this demo working.

What you will need

  1. The following Javascript content:

     

    <script type=”text/javascript”>

    var context = null;

    var web = null;

    function deleteAllItems()

    {

    var okToContinue = confirm(“Are you sure you want to delete all items in this list?”);

    if(okToContinue)

    {

    context = new SP.ClientContext.get_current();

    web = context.get_web();

    context.load(web);

    var ID = SP.ListOperation.Selection.getSelectedList();

    curList = web.get_lists().getById(ID);

    context.load(curList);

     

    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml(“<View><Query><Where><Geq><FieldRef Name=’ID’ /><Value Type=’Number’>1</Value></Geq></Where></Query></View>”);

    this.collListItem = curList.getItems(camlQuery);

    context.load(collListItem);

     

    context.executeQueryAsync(Function.createDelegate

    (this, this.onSuccessGetList, Function.createDelegate,

    this, this.onFailure));

    }

    }

    function onSuccessGetList(sender, args)

    {

    var listItemEnum = collListItem.getEnumerator();

    var counter = 0;

    var itemArr = new Array();

    while(listItemEnum.moveNext())

    {

    var listItem = listItemEnum.get_current();

    itemArr[counter] = listItem.get_item(“ID”);

    counter++;

    }

     

    for(var id in itemArr)

    {

    var spItem = curList.getItemById(itemArr[id]);

    spItem.deleteObject();

    }

     

    context.executeQueryAsync(Function.createDelegate

    (this, this.onSuccessClean, Function.createDelegate,

    this, this.onFailure));

    }

     

    function onSuccessClean(sender, args)

    {

    alert(“All items deleted!”);

    window.location = window.location.href;

    }

     

    function onFailure(sender, args)

    {

    alert(“Error”);

    }

    </script>

     

  2. The following Ribbon Extension XML definition:
    <?xml version=”1.0″ encoding=”utf-8″?>

    <Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>

    <CustomAction

    Id=”Techdays.Ribbon.Action”

    Location=”CommandUI.Ribbon”

    RegistrationId=”100″

    RegistrationType=”List”>

    <CommandUIExtension>

    <CommandUIDefinitions>

    <CommandUIDefinition Location=”Ribbon.Tabs._children”>

    <Tab Id=”Techdays.Ribbon.Tab”

    Sequence=”550″

    Description=”Techdays Demo Tab”

    Title=”Techdays” CssClass=”TechdaysTabGroup”>

    <Scaling

    Id=”Techdays.Ribbon.Tab.Scaling”>

    <MaxSize Id=”Techdays.Ribbon.Tab.MaxSize” GroupId=”Techdays.Ribbon.Tab.Group” Size=”OneLarge”/>

    <Scale Id=”Techdays.Ribbon.Tab.Scaling” GroupId=”Techdays.Ribbon.Tab.Group” Size=”OneLarge”/>

    </Scaling>

    <Groups Id=”Techdays.Ribbon.Tab.Groups”>

    <Group Id=”Techdays.Ribbon.Tab.Group” Description=”Techdays Ribbon Custom Group” Title=”Techdays”

    Sequence=”20″

    Template=”Techdays.Ribbon.Tab.Template” >

    <Controls Id =”Techdays.Ribbon.Tab.Controls”>

    <Button

    Id=”Techdays.Ribbon.Tab.Group.TestButton”

    Command=”DeleteAllItems”

    Sequence=”10″

    Description=”Delete All Items”

    LabelText=”Clean all items in List”

    TemplateAlias=”TechdaysTemplateAlias”

    Image32by32=”/_layouts/images/warning32by32.gif”

    />

    </Controls>

    </Group>

    </Groups>

    </Tab>

    </CommandUIDefinition>

    <CommandUIDefinition Location=”Ribbon.Templates._children”>

    <GroupTemplate Id=”Techdays.Ribbon.Tab.Template”>

    <Layout Title=”OneLarge” LayoutTitle=”OneLarge”>

    <Section Alignment=”Top” Type=”OneRow”>

    <Row>

    <ControlRef DisplayMode=”Large” TemplateAlias=”TechdaysTemplateAlias”/>

    </Row>

    </Section>

    </Layout>

    </GroupTemplate>

    </CommandUIDefinition>

    </CommandUIDefinitions>

    <CommandUIHandlers>

    <CommandUIHandler Command=”DeleteAllItems” CommandAction=”javascript:deleteAllItems();” />

    </CommandUIHandlers>

    </CommandUIExtension>

    </CustomAction>

    </Elements>

     

Steps to Follow

  1. Copy the Javascript content above in your master page, just before the closing </head> tag

  2. Save your changes back to the server;
  3. Launch Visual Studio and create a new Empty SharePoint Project, naming it whatever you feel like

  4. When prompted, make sure you chose to use a Sandboxed Solution, and not a farm one

  5. In the newly created project, add a new Empty Element

  6. In the newly created item, inside of elements.xml, copy and paste the ribbon extension content above.
  7. Build your solution;
  8. Grab the .wsp file produced and deploy on your site via the solutions gallery
  9. Activate the solution

  10. Navigate to any Custom List, you should now see your new ribbon extension under the “Techdays” tab

     

The full solution file can be downloaded at http://nikcharlebois.sharepointspace.com/Solutions/DeleteAllItems.wsp . Enjoy!

 

Nik,

Onboard of Train 59 back from Techdays

Microsoft Premier Field Engineer – SharePoint

Leave a Comment

Your email address will not be published. Required fields are marked *

*
*