Search code examples
javascriptextjs4.1

Remember the state of extjs 4 checkbox


In my form panel I added a checkbox, setting:

stateful: true,
stateId: 'loginPanelRemeberMe'

then, before sending form I save state calling:

this.saveState()

on the panel. All other componenets save their state and whe I reload the page they recall the previous state, but checkbox alway start in unchecked state. Is there any way to force save value?


Solution

  • This works for me:

    In your Application launch function (or in a controller init function), add the following:

    if( Ext.supports.LocalStorage )
    {
        Ext.state.Manager.setProvider(new Ext.state.LocalStorageProvider());
    }
    else
    {
        Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    }
    

    Then define your checkbox in a view and override the getState and applyState functions:

    {
        xtype: 'checkboxfield',
        getState: function() {
            return { "checked": this.getValue() };
        },
        applyState: function(state) {
            this.setValue( state.checked );
        },
        stateEvents: [
            'change'
        ],
        stateId: 'myCheckBox',
        stateful: true,
        id: 'myCheckBox',
    }
    

    Tested to work with ExtJS 4.2 and 6.5.x.

    Note for Sencha Architect users: If you defined a view as your initial view, a hidden Ext.create line like Ext.create('YourApp.view.MainPanel') is added automatically by Sencha Architect on top of your launch function. That will have the undesirable effect of instantiating your view before your state provider can be initialized, and so your fields applyState function will never get called.

    Solution: un-mark your view as the initial view, and add the Ext.create line manually after your state provider is initialized.