Monday, April 20, 2009

Ext expandable grid rows, now with AJAX

Ext homepage shows an example of a grid with expandable rows. However, the data in the expanded rows is loaded together with all the data in the grid. I needed to change this behaviour so the data would be loaded with an AJAX request, only after the row is expanded. So here is what I did:

First, download the RowExpander plugin, which is used in the example. Next, replace the getBodyContent method with:

getBodyContent : function(record, index, body){
if(!this.enableCaching){
return this.tpl.apply(record.data);
}

var content = this.bodyContent[record.id];
if(!content){
var th = this;
Ext.Ajax.request({
url: this.url,
method: "GET",
params: { id: record.id },
success: function(res) {
var result = eval("("+res.responseText+")");
var content = th.tpl.apply(result);
th.bodyContent[record.id] = content;
body.innerHTML = content;
},
failure: function(res) {
content = "Error loading data";
body.innerHTML = content;
}
});
content = "Loading...";
this.bodyContent[record.id] = content;
}
return content;
}

As you can see, the method signature has been changed, so you have to add body to the method invocation in beforeExpand method. Also, the url to the AJAX service has to be smuggled somehow - I just passed it in the RowExpander initialization parameters.

This probably is not the most elegant solution to this issue - but it has one great advantage: it works :).

No comments: