Dojo Data Grid – Part 25: Deleting Selected Documents

In this post, I’ll show how you can add the ability to delete documents from a Dojo Data Grid control in XPages.

Dojo Data Grid Series

Dojo Grids in XPages — All Blog Posts

REST service type

As I mentioned in an earlier post on editing data in the grid, the type of REST service is important when dealing with updating grid data.

With a viewItemFileService, you can delete documents via the grid as long as you have the rights within the application. With a viewJsonService, you cannot delete documents by default, but you can allow it if you enable data services on your server and your Web Site document allows DELETE operations.

The Code

In order to delete selected documents from a grid, put this client-side JavaScript code on a button on the page and it will do the trick.

// Get all selected items from the Grid:
var items = djxDataGrid1.selection.getSelected();
if(items.length){
  dojo.forEach(items, function(selectedItem){
    if(selectedItem !== null){
      djxDataGrid1.store.deleteItem(selectedItem);     
    }
  });
  var args = {onError: function() {alert('error!');}};
  djxDataGrid1.store.save(args); 
} 

The code assumes the default grid name of djxDataGrid1; adjust it accordingly if your grid has a different name.

The code walks through all selected items and removes them. When done, it saves the updates to the REST service. Without the save, it would remove the rows from the grid but then refresh the page and display them again, because they weren’t actually deleted.

Handling Errors

The save method of the REST service accepts an argument with a callback function. In this example, I’m displaying an alert message if the deletion fails.

The error will be displayed if the user does not have proper rights to delete documents or if the server does not allow deletions for the current type of REST service.

Other Options

Here are two additional ways that you might want to trigger this code if you’d like a different user experience:

  1. You could have an icon or button display in a grid cell that triggers code when clicked (via a formatter function). This would require a bit of a different approach to be aware of the row that is being clicked, but it’s doable.
  2. If you’re using an EnhancedGrid, you could implement context menus and make row deletion a row context menu options
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: