Hi
I'm very new to extjs and javascript world but I created very simple extension for Ext.grid.Panel.
Extension is autogenerating columns based on Ext.data.Model for grid.
My implementation is very simple but you can see how to do that. It is very easy to make changes to your needs.
Extension:
Code:
/**
* Lukas Sliwinski - auto generate columns in grid based on model
* sliwinski.lukas@gmail.com
*/
Ext.override(Ext.grid.Panel, {
initComponent: function() {
this.autoGenerateColumn();
this.callParent(arguments);
}
});
Ext.define('Ext.grid.AutoGenerateColumn', {
autoGenerateColumn: function() {
var me = this,
noModel = Ext.isDefined(me.model) === false,
noAutoGenerate = Ext.isDefined(me.autoGenerateColumns) === false;
if (noModel && noAutoGenerate) {
return;
}
if (me.autoGenerateColumns === true) {
if(Ext.isString(me.model)) {
me.model = Ext.ModelManager.getModel(me.model);
}
var modelFields = me.model.prototype.fields;
me.columns = new Array();
// Adding columns to grid
for (var i=0; i < modelFields.length; i++) {
var modelField = modelFields.items[i];
var isVisible = (Ext.isDefined(modelField.visible) && (modelField.visible === true));
if (isVisible) {
var column = {
header: modelField.name,
dataIndex: modelField.name
};
if (modelField.type.type === 'floatOrString') {
column.renderer = Ext.util.Format.numberOrString;
}
me.columns.push(column);
}
}
}
if (me.columns.length == 0) {
Ext.Error.raise('No fields declared in ' + me.model.$className + ' with property visible. Columns will not be created!');
}
}
});
Ext.grid.Panel.mixin('AutoGenerateColumn', Ext.grid.AutoGenerateColumn);
The most interesting part is below green comment.
In this place you can make some changes that will meet your requirements.
In my version I estabilised that in fields of model will be property visible type of boolean and only that fileds will be used to create columns.
I have also add some conditions like I created for my own type floatOrString:
Code:
if (modelField.type.type === 'floatOrString') {
column.renderer = Ext.util.Format.numberOrString;
}
Example of model:
Code:
Ext.define('AppName.model.SomeModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'}, // column will be not created
{name: 'name', type: 'string', visible: true},
{name: 'value', type: 'floatOrString', visible: true},
{name: 'data', type: 'string', visible: true},
{name: 'email', type: 'string', visible: false} // column will be not created
]
Example how declare grid with autoGenerateColumn extension:
Code:
Ext.define('AppName.view.SomeGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.someGrid
autoGenerateColumns: true, // Need to be set
model: 'AppName.model.SomeModel', // Need to be set
store: 'AppName.store.SomeStore'
}
I have tested this extension only with Extjs 4.1.
Fill free to use.
Best regards,
Lukas