Search code examples
extjsextjs6.2tagfield

EXTJS 6.2 Disabled Already Selected Tags in Tag Field


In a tag field is there a way to prevent already selected tags from being removed or disable them? I have a use case where I want to allow users to add additional tags but not remove any existing tags.


Solution

  • There is a way, it requires the following configs:

    1. To disable deselection by clicking on an already selected item, set up a beforedeselect listener and return false from it to cancel the deselect.
    2. To disable removal by editing the field and pressing the delete button, set editable to false. It also requires setting selectOnFocus to false.

    There are two other optional configs you could consider:

    1. Set filterPickList to true. This will remove the selected item from the selection list.
    2. Get rid of the x trigger from the right top corner of tags. This can be done by setting tagItemCloseCls to null. (There will be some empty space at the right side - if you want to remove it you need further customization, possibly some kind of override.)

    Putting it all together the code looks something like this, you can try this in a Sencha Fiddle:

    Ext.application({
        name: 'Fiddle',
        launch: function () {
    
            var store = Ext.create('Ext.data.Store', {
                fields: ['id', 'name'],
                data: [{
                    id: 1,
                    name: 'One'
                }, {
                    id: 2,
                    name: 'Two'
                }, {
                    id: 3,
                    name: 'Three'
                }, {
                    id: 4,
                    name: 'Four'
                }, {
                    id: 5,
                    name: 'Five'
                }, ]
            });
    
            Ext.create('Ext.form.Panel', {
                renderTo: Ext.getBody(),
                title: '"One way" tagfield',
                items: [{
                    xtype: 'tagfield',
                    store: store,
                    displayField: 'name',
                    valueField: 'id',
                    queryMode: 'local',
                    selectOnFocus: false,
                    editable: false,
                    width: 400,
                    filterPickList: true,
                    tagItemCloseCls: null,
                    listeners: {
                        beforedeselect: function (tagfield, record, index, eOpts) {
                            return false;
                        }
                    }
                }]
            });
        }
    });