欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[置顶] Extjs4 grid根据model自动生成列

程序员文章站 2022-05-04 18:07:36
...
/**
 * model中设置visible属性使该列可生成,设置editor可以传递编辑器,
 * model中设置columnName可传递列名,默认为model的name为列名
 * grid中设置autoGenerateColumns: true,可使自动生成列 
 * author:[email protected]
 */
Ext.override(Ext.grid.Panel, {
    initComponent: function() {
        this.autoGenerateColumn();
        this.callParent(arguments);
    }
});


Ext.define('Ext.ux.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));
				var columnName;
                if (isVisible) {
                	columnName=modelField.name;
                	if(Ext.isDefined(modelField.columnName)){
                		columnName=modelField.columnName;
                	}
                    var column = {
                        text: columnName,
                        dataIndex: modelField.name
                    };

                    if (modelField.type.type === 'floatOrString') {
                        column.renderer = Ext.util.Format.numberOrString;
                    }
					if(Ext.isDefined(modelField.editor)){
						column.editor=modelField.editor;
					}
                    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.ux.AutoGenerateColumn);

相关标签: 个人