Friday, 29 August 2014

ExtJS4 Dynamic Grid

In the MV* patterns, model refers to the fixed state of content. If state changes then the benefit that comes out of this model is trivial. Some times it could be a case that model is dynamic, in such a case ExtJS grid should be constructed dynamically. Here is how the sample code goes...

ExtJS4 grid has a method called reconfigure which takes store and columns as input arguments and restructures grid. These columns and store depends on the field data which a part of model. Since model is dynamic lets create field data dynamically along with the actual data and send it to the server.



this.grid = Ext.widget('grid', {
store: null,
columns: null
});
Ext.Ajax.request({
url: '/dynamicGridData',
callback: this.buildDynamicGrid,
scope: this
});
buildDynamicGrid: function(options, success, response) {
var data = Ext.decode(response.responseText);
var fielddata = new Array();
var columndata = new Array();
Ext.Array.forEach(data.headers, function(header) {
Ext.Array.push(columndata, {
text: header.text,
dataIndex: header.dataIndex
});
Ext.Array.push(fielddata, {
name: header.dataIndex
});
});
var store = Ext.create('Ext.data.ArrayStore', {
fields: fielddata,
data: data.rows
});
var columns = columndata
this.grid.reconfigure(store, columns)
}
view raw DynamicGrid.js hosted with ❤ by GitHub
Here is the structure from server
public class DynamicGrid {
private List
headers;
private List fields;
private List> rows;
public List> getRows() {
return rows;
}
public void setRows(List> rows) {
this.rows = rows;
}
public List getFields() {
return fields;
}
public void setFields(List fields) {
this.fields = fields;
}
public List
getHeaders() {
return headers;
}
public void setHeaders(List
headers) {
this.headers = headers;
}
public void addField(String string) {
if (this.fields == null) {
this.fields = new ArrayList<>();
}
this.fields.add(string);
}
public void addHeader(Header header) {
if (this.headers == null) {
this.headers = new ArrayList<>();
}
this.headers.add(header);
}
public void addRow(List row) {
if (this.rows == null) {
this.rows = new ArrayList<>();
}
this.rows.add(row);
}
}
public class Header {
private String text;
private String dataIndex;
public Header(String text, String field) {
this.text = text;
this.dataIndex = field;
}
}

No comments:

Post a Comment