根据 Dynamic Grid 重新整理了一个适合在 extjs2.2 版本下使用的动态 editGridPanel。
代码如下:
Ext.grid.DynamicColumnModel = function(store){
var cols = [];
var recordType = store.reader.recordType;
var fields = recordType.prototype.fields;
if (fields.length == 0) {
fields = store.reader.headers;
for (var i = 0; i < store.reader.headers.length; i++) {
var header = store.reader.headers[i]
cols[i] = {
header: header.text,
dataIndex: header.name,
tooltip: '',
hidden: header.hidden,
renderer: eval(header.renderer)
};
}
}
else {
for (var i = 0; i < fields.keys.length; i++) {
var fieldName = fields.keys[i];
//add checkbox column
if (fieldName == "__chkbox") {
cols[i] = new Ext.grid.CheckboxSelectionModel();
continue;
}
//add checkbox column
if (fieldName == "__rownum") {
cols[i] = new Ext.grid.RowNumberer();
continue;
}
var field = recordType.getField(fieldName);
cols[i] = {
header: field.header,
dataIndex: field.name,
tooltip: field.tooltip,
hidden: field.hidden,
sortable: true,
renderer: eval(field.renderer),
editor: new Ext.form.TextField()
};
}
}
store.fields = store.reader.recordType.prototype.fields;
Ext.grid.DynamicColumnModel.superclass.constructor.call(this, cols);
};
Ext.extend(Ext.grid.DynamicColumnModel, Ext.grid.ColumnModel, {});
Ext.data.DynamicXmlReader = function(meta){
meta = meta ||{};
Ext.data.XmlReader.superclass.constructor.call(this, meta,meta.fields);
};
Ext.extend(Ext.data.DynamicXmlReader, Ext.data.XmlReader, {
getRecordType: function(data){
recordDefinition = Ext.DomQuery.select(this.meta.recordDefinition + ' > *', data);
var arr = [];
j = 0;
for (var i = 0; i < recordDefinition.length; i++) {
if (recordDefinition[i].nodeType == 1) {
arr[j] = {
name: recordDefinition[i].tagName,
header: recordDefinition[i].getAttribute('header'),
tooltip: recordDefinition[i].getAttribute('tooltip'),
hidden: recordDefinition[i].getAttribute('hidden') == "true" ? true : false,
renderer: recordDefinition[i].getAttribute('renderer')
};
j++;
}
}
this.recordType = Ext.data.Record.create(arr);
return this.recordType;
},
readRecords: function(doc){
this.xmlData = doc;
var root = doc.documentElement || doc;
this.getRecordType(root);
return Ext.data.DynamicXmlReader.superclass.readRecords.call(this, doc);
}
});
Ext.grid.DynamicGrid = function(container){
Ext.grid.DynamicGrid.superclass.constructor.call(this, container, []);
};
Ext.extend(Ext.grid.DynamicGrid, Ext.grid.EditorGridPanel, {
onRender: function(ct, position){
this.store.on('load', this.doReconfiguration, this);
this.colModel = new Ext.grid.ColumnModel([{
header: '',
dataIndex: '',
sortable: true
}]);
Ext.grid.DynamicGrid.superclass.onRender.call(this, ct, position);
},
doReconfiguration: function(){
this.colModel = new Ext.grid.DynamicColumnModel(this.store);
this.view.bind(this.store, this.colModel);
this.view.refresh(true);
this.store.removeListener("load", this.doReconfiguration);
}
});