Ошибка отображения ExtJS EditorGridPanel

У меня проблема с Ext.Grid.EditorGridPanel, в настоящее время я использую ExtJS 2.3.0, который нельзя изменить. :-(

После проблемы:

Я создал окно, состоящее из двух FormPanel и между ними EditorGridPanel. Для viewConfig сетки существует только набор "forceFit = true", а для ColumnModel не установлены параметры стиля или представления. Только для каждого столбца параметр выравнивания установлен на «центр». ColumnModel состоит из 13 столбцов, более или менее текстовых. Теперь я открываю веб-сайт, над которым работаю, в браузере и открываю окно, чтобы протестировать графический интерфейс. Когда я пытаюсь переключиться между ячейками в одной строке, вся строка данных перемещается влево, так что первые ячейки больше не отображаются. После добавления новой строки в сетку (с помощью кнопки добавления) вид сбрасывается, и все ячейки для каждого столбца снова отображаются правильно. Заголовки столбцов и тбар фиксированы и всегда правильно отображаются.

Проблема возникает с IExplorer 8.0x, более старой версией Firefox (2.0x), но сетка отлично работает с Firefox 3.6x и Safari 5.0x. Если у кого-то была похожая проблема и он решил ее или возникла идея, что может вызвать эту проблему, не стесняйтесь отвечать. ;-) Спасибо заранее!

[править] Спасибо за комментарий, здесь некоторый измененный Источник из полного источника:

getTypeSelectionGrid: function() {
    this.gridRecord:  Ext.data.Record.create([
        {name:'id', type:'int'},
        {name:'start', type:'string'},
        {name:'end', type:'string'},
        {name:'mo', type:'boolean'},
        {name:'tu', type:'boolean'},
        {name:'we', type:'boolean'},
        {name:'th', type:'boolean'},
        {name:'fr', type:'boolean'},
        {name:'sa', type:'boolean'},
        {name:'su', type:'boolean'},
        {name:'type', type:'string'}
    ]);

    this.gridStore = new Ext.data.Store({
        baseParams: {
        },
        sortInfo: {field: 'id', direction: 'ASC'},
        proxy: new Ext.data.HttpProxy({
            url: '',
            method: 'post'
        }),
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'id'
        }, this.gridRecord)
    });

    var sm = new Ext.grid.RowSelectionModel({ singleSelect: true });

    var columnConfig = [];
    //auto incremented id column
    columnConfig.push({ 
        header: 'id',
        dataIndex: 'id',
        width: 50,
        editor: new Ext.form.TextField({
            anchor: '100%',
            allowBlank: false,
            disabled: true
        })
    });
    //start value for time range, values from '00:00' to '24:00' steps by second, here shorted to 2 options
    columnConfig.push({
        header: 'start',
        dataIndex: 'start',
        width: 70,
        align: 'center',
        editor: new Ext.form.ComboBox({
            store: new Ext.data.SimpleStore({
                fields: ['val', 'txt'],
                data : [['00:00', '00:00'],['24:00', '24:00']]
            }),
            displayField: 'txt',
            valueField: 'val',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            selectOnFocus: true,
            saveRouting: true,
            forceSelection: true,
            anchor: '100%',
            allowBlank: false
        })
    });
    //same as above for end of time range, dataIndex 'end'

    //now 7 checkbox columns foreach weekday
    columnConfig.push({
        xtype: 'checkcolumn',
        header: 'mo',
        dataIndex: 'mo',
        align: 'center',
        width: 30
    }));
    //same as above for dataIndex 'tu', 'we', 'th', 'fr', 'sa' and 'su'

    //here simplified to SimpleStore, originally a remote store which gets the data
    //by a HttpProxy
    columnConfig.push({
        header: 'type',
        dataIndex: 'type',
        editor: new Ext.form.ComboBox({
            store: new Ext.data.SimpleStore({
                fields: ['val', 'txt'],
                data : [[1, 'type 1'],[2, 'type 2']]
            }),
            displayField: 'txt',
            valueField: 'txt',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            selectOnFocus: true,
            saveRouting: true,
            forceSelection: true,
            anchor: '100%',
            allowBlank: false
        })
    });
    //then 2 plugins which have some functionality for the selected row
    //grid tested with and without both plugins, they are not the cause

    var cm = new Ext.grid.ColumnModel(columnConfig);
    cm.defaultSortable = false;

    //now the grid
    this.typeSelectionGrid = new Ext.grid.EditorGridPanel({
        store: this.gridStore,
        clicksToEdit: 1,
        autoHeight: true,
        cm: cm,
        sm: sm,
        viewConfig: {
            forceFit: true
        },
        tbar: [{
            text: 'add new row',
            cls: 'x-btn-text',
            scope: this,
            handler: function(){
                //adds a row with incremented id
            }
        }],
        listeners: {
            scope: this,
            show: function() {
                sm.selectFirstRow.defer(1000, selectionModel);
            }
        }
    });

    return this.typeSelectionGrid;
},

//the grid is then inserted between the Panels into the window component
//looks something like that
render: function() {

    var layoutFn = function(pnl) {
        pnl.ownerCt.ownerCt.doLayout.defer(Ext.isIE ? 300 : 0, pnl.ownerCt.ownerCt);
        pnl.doLayout.defer(Ext.isIE ? 500 : 200, pnl);
    };
    this.cardLayout.add({
        layout: 'border',
        border: false,
        bodyStyle: 'background-color: #fff',
        items: [
            {
                region: 'center',
                border: false,
                layout: 'column',
                autoScroll: true,
                defaults: {
                    columnWidth: 1,
                    bodyStyle: 'padding: 5px;',
                    border: false,
                    autoHeight: true,
                    layout: 'column',
                    defaults: {
                        columnWidth: 1
                    }
                },
                items: [
                    //first Ext.form.FormPanel with some TextFields
                    {
                        items: {
                            listeners: {
                                expand: layoutFn,
                                collapse: layoutFn
                            },
                            frame: true,
                            title: 'panel with a grid',
                            collapsible: true,
                            titleCollapse: true,
                            layout: 'fit',
                            autoHeight: true,
                            items: this.getTypeSelectionGrid()
                        }
                    }
                    //second Ext.form.FormPanel with some TextFields
                ]
            }
        ]
    });
}

person kockiren    schedule 25.01.2011    source источник
comment
Если бы вы могли опубликовать образец кода, было бы здорово и отладку :) Ура   -  person Lionel Chan    schedule 25.01.2011
comment
спасибо Лайонел, я добавляю в статью источник.   -  person kockiren    schedule 26.01.2011


Ответы (2)


Во-первых, похоже, что у вас есть синтаксические ошибки JavaScript. Я знаю, что вы разместили только фрагмент своего кода, но попробуйте запустить все это через JS Lint.

Для начинающих:

this.gridRecord:  Ext.data.Record.create([
    {name:'id', type:'int'},
    {name:'start', type:'string'},
    {name:'end', type:'string'},
    {name:'mo', type:'boolean'},
    {name:'tu', type:'boolean'},
    {name:'we', type:'boolean'},
    {name:'th', type:'boolean'},
    {name:'fr', type:'boolean'},
    {name:'sa', type:'boolean'},
    {name:'su', type:'boolean'},
    {name:'type', type:'string'}
]);

Должно быть:

this.gridRecord = Ext.data.Record.create([

Хотя я не совсем уверен, что это вызовет проблему, я вижу, что вашим конфигурациям столбцов назначена ширина. Даже если вы устанавливаете свойство viewConfig "forceFit: true", я подозреваю, что редактор может попытаться использовать ширину, которую вы установили для каждого столбца.

Посмотрим, проясняет ли это что-нибудь.

person arthurakay    schedule 26.01.2011

Спасибо, но во фрагменте кода есть ошибка копирования и вставки, gridRecord является глобальным свойством в исходном коде. Я упустил это из виду, когда изменил код, извините за путаницу.

Теперь я попробовал ваше предложение и нашел виновника: похоже, что IE вообще не может обрабатывать параметр "forceFit", я закомментировал этот параметр и установил ширину для каждого столбца и ... он работал нормально, столбец не перемещается! Нет, я вставил обходной путь, сначала я проверяю, является ли браузер IE, если для параметра forceFit установлено значение «true», иначе «false».

Большое спасибо за вашу помощь!

person kockiren    schedule 26.01.2011