How to refresh datagrid

Damir picture Damir · Mar 31, 2011 · Viewed 41.3k times · Source

I create dojox.grid.datagrid and I fill content from array like on example last example on page. During time, I change value of that array in code. How to refresh content of that grid ? How to load new data from changed array ?

Answer

Tom Gruner picture Tom Gruner · Apr 1, 2011

To change values in the grid, you will need to change the value in the grid's store. The grid data is bound to the store data, and the grid will update itself as needed.

So the key is to understand Dojo's data api and how stores work in Dojo. Rather than manipulating the data directly in the grid, manipulate it in the store.

Ideally, the store is your array that you manipulate as the application runs and you should not be needing to sync the array to the grid. Just use the ItemFileWriteStore as your data holder unless thats not possible.

Also, using the dojo data identity api makes it much simple to find items in the grid if that is possible. Assuming you know when an item is updated, deleted, or changed in your application you should be able to modify the grid store as needed when the action happens. This is definitely the preferred approach. If you can't do that you will have to do a general fetch and use the onComplete callback to manually sync your arrays which will be very slow and won't scale well, in which case you may as well just create a new store all together and assign it to the grid with grid.setStore(myNewStore)

Here is a fiddle with a basic create, update, and delete operation: http://jsfiddle.net/BC7yT/11/

These examples all take advantage of declaring an identity when creating the store.

var store = new dojo.data.ItemFileWriteStore({
    data: {
        identifier : 'planet',
        items: itemList
    }
});

UPDATE AN EXISITNG ITEM:

//If the store is not in your scope you can get it from the grid
var store = grid.store;
//fetchItemByIdentity would be faster here, but this uses query just to show 
//it is also possible
store.fetch({query : {planet : 'Zoron'},
             onItem : function (item ) {

                  var humans = store.getValue(item, 'humanPop');
                  humans += 200;
                  store.setValue(item, 'humanPop', humans);

              }
        });

INSERT A NEW ITEM:

store.newItem({planet: 'Endron', humanPop : 40000, alienPop : 9000});
               } catch (e) { 
                  //An item with the same identity already exists
               }

DELETE AN ITEM:

store.fetchItemByIdentity({ 'identity' : 'Gaxula',  onItem :  function (item ) {
    if(item == null) {
         //Item does not exist
    } else {
        store.deleteItem(item);
    }
}});