ExtJs 4: How do I hide/show grid columns on the fly?

extjs4

Solution

The following should work:

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    id: 'simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    columns: [
        { text: 'Name',  dataIndex: 'name' },
        { text: 'Email', dataIndex: 'email', flex: 1 },
        { text: 'Phone', dataIndex: 'phone' }
    ],
    height: 200,
    width: 400,
    renderTo: Ext.getBody(),
    dockedItems:[{
        xtype:'button',
        handler: function() {
            if(Ext.getCmp('simpsons').columns[0].isVisible())
                Ext.getCmp('simpsons').columns[0].setVisible(false);
            else
                Ext.getCmp('simpsons').columns[0].setVisible(true);
        }
    }]
});

Problem

I need to show/hide columns of a grid on the fly, but it seems that ExtJs 4 has no implemented method for that. In previous versions I should use columnModel, what doesn't exist anymore. Just get `grid.columns[index]` and `hide()` or `show()` doesn't affect the grid. Use `grid.columnManaget.getColumns()[index].hide()` can really hide the column, but it cannot be shown again (as `getColumns()` does not return that column after that).

Original source