Search code examples
javascriptextjscombobox

How to disable items in a combobox in Ext JS?


How can I disable specific items in a combobox in Ext JS?

For example I have these records

row_1_type_1
row_2_type_2
row_3_type_3

and I want to disable the third row i.e it should stay in the combo as label but it will be greyed out and not clickable.


Solution

  • Here's a solutions that you can use at least for Ext JS 4.2.1. It's a plugin that disables some items in the boundlist based on the value of each record. The name of the field to check if the listitem should be disabled can be configured.

    Let's start with how to use the plugin.

    {
        xtype: 'combo',
        fieldLabel: 'My combo with disabled items',
        valueField: 'value',
        displayField: 'display',
        queryMode: 'local',
        store: {
            fields: ['value', 'display', 'disabled'],
            data: [{
                value: 1, display: 'an enabled item', disabled: false
            },{
                value: 2, display: 'a disabled item', disabled: true
            }]
        },
        plugins: [{
            ptype: 'comboitemsdisableable',
            disabledField: 'disabled'
        }]
    }
    

    And here's the plugin.

    Ext.define('Ext.ux.plugin.ComboItemsDisableable', {
        extend: 'Ext.AbstractPlugin',
        alias: 'plugin.comboitemsdisableable',
    
        init: function (cmp) {
            var me = this; // the plugin
            me.disabledField = me.disabledField || 'disabled';
    
            cmp.tpl = Ext.create('Ext.XTemplate',
                '<tpl for=".">',
                '  <tpl if="this.isDisabled(' + me.disabledField + ')">',
                '    <div class="x-boundlist-item x-item-disabled"><em>{' + cmp.displayField + '}</em></div>',
                '  <tpl else>',
                '    <div class="x-boundlist-item">{' + cmp.displayField + '}</div>',
                '  </tpl>',
                '</tpl>', {
                    isDisabled: function(disabled) {
                        return disabled;
                    }
                }
            );
    
            // make sure disabled items are not selectable
            cmp.on('beforeselect', function(combo, record, index) {
                return !record.get(me.disabledField);
            });
        }
    });
    

    And here's some css to go with the plugin. It greys out the disabled items and makes sure that the disabled items when hovered don't get its background changed as to suggest that it would be selectable.

    .x-item-disabled.x-boundlist-item {
        color: #8c8c8c;
        cursor: default;
    }
    
    .x-item-disabled.x-boundlist-item-over {
        background: inherit;
        border-color: white;
    }