Ext.define('Ext.grid.DynamicStatefulGridPanel', {
extend: 'Ext.grid.Panel',
alias: 'widget.dynamicstatefulgrid',
stateful: true,
initComponent: function() {
var _this = this;
this.on({
beforestatesave: function(cmp, state, eOpts) {
var savedState = Ext.state.Manager.getProvider().state[_this.stateId];
// don't save a state of 0 columns shown
if (state && state.columns.length === 0 && savedState && savedState.columns.length === 0) {
return false;
}
// if the current state has 0 columns shown, replace it with the old state and
// return false to prevent saving an empty state
if (state.columns.length === 0 && savedState && savedState.columns.length > 0) {
state = savedState;
return false;
}
// if a metachange event was fired previously, reset the metachangefired flag
// to prevent saving the incorrect state
if (_this.store.metachangefired) {
_this.store.metachangefired = false;
return false;
}
// if new state and old state are present, update the column hidden and width attributes
if (state && state.columns.length > 0 && savedState && savedState.columns.length > 0) {
$.each(savedState.columns, function(index, savedColumn) {
$.each.(state.columns, function(stateIndex, newColumn) {
if (savedColumn['id'] === newColumn['id']) {
if (savedColumn['hidden'] && newColumn['hidden'] != false) {
newColumn['hidden'] = savedColumn['hidden'];
}
if (!newColumn['width'] && savedColumn['width']) {
newColumn['width'] = savedColumn['width'];
}
}
});
});
}
_this.metachangefired = false;
},
beforereconfigure: function(cmp, store, columns, oldStore, oldColumns, eOpts) {
_this.store.metachangefired = false;
}
});
this.callParent(arguments);
},
bindStore: function(store) {
var _this = this;
//initialize the metachangefired flag on the store
store.metachangefired = false;
this.callParent(arguments);
store.mon(store, 'metachange', function(store, meta) {
store.metachangefired = true;
// get the columns passed in on the metachange event.
// Note: these columns don't have the savedState applied yet
var metaDataColumns = meta.columns;
// initialze array to track saved state column order
var reorderedMetaColumns = [];
var provider = Ext.state.Manager.getProvider();
var state = provider.state;
// if a state is present for this grid (_this.stateId), update the columns
// with the saved state from the state provider
if (state[_this.stateId]) {
$.each(metaDataColumns, function(index, metaDataColumn) {
$.each(state[_this.stateId]['columns'], function(stateIndex, stateColumn) {
if (metaDataColumn['dataIndex'] === stateColumn['id']) {
if (stateColumn['hidden']) {
metaDataColumn['hidden'] = stateColumn['hidden'];
}
if (stateColumn['width']) {
metaDataColumn['width'] = stateColumn['width'];
}
}
});
});
}
if (reorderedMetaColumns.length === 0) {
reorderedMetaColumns = metaDataColumns;
}
// reconfigure the grid with the saved state applied to
// the dynamic metaData columns
_this.reconfigure(store, reorderedMetaColumns);
}
}
});