Pages

Saturday, January 23, 2010

ExtJS -=- Search field with clearable functionality

Here is a new ExtJS component. It shows a search field that works like a clearable combo box. It has the same configuration than the Ext.form.ComboBox. You can enter some informations (minimum 3 characters) and the component will find the corresponding data in the JSON store. When entering data a clearable trigger appears so you can clear the combo.



Ext.namespace("Ext.Ice");

Ext.Ice.SearchField = Ext.extend(Ext.form.ComboBox, {
    /**
     * The triggers icons
     */
    trigger1Class: 'x-form-clear-trigger',
    trigger2Class: 'x-form-search-trigger',

    selectOnFocus: true,
    forceSelection: true,
    editable: true,

    /**
     * Type ahead config
     */
    typeAhead: true,
    typeAheadDelay: 1000,
    minChars: 3,
    
    /**
     * Hide the clear trigger by default
     */
    hideTrigger1: true,

    /**
     * Grabbing config from TwinTrigger Field
     */
    initComponent: Ext.form.TwinTriggerField.prototype.initComponent,
    getTrigger: Ext.form.TwinTriggerField.prototype.getTrigger,
    initTrigger: Ext.form.TwinTriggerField.prototype.initTrigger,

    /**
     * Reset function to hide the clear icon
     */
    reset : Ext.form.Field.prototype.reset.createSequence(function() {
        this.triggers[0].hide();
    }),


    /**
     * Show the clear trigger icon
     */
    onViewClick: Ext.form.ComboBox.prototype.onViewClick.createSequence(function() {
        this.triggers[0].show();
    }),

    /**
     * Trigger for the search functionnality
     */
    onTriggerClick : function() {
        if (this.getRawValue().length < 3) {
            Ext.Msg.show({
                title:'Please refine your search',
                msg: 'Please refine your search by entering at least 3 characters.',
                buttons: Ext.Msg.OK,
                animEl: 'elId',
                icon: Ext.MessageBox.INFO
            });
        } else {
            Ext.Ice.SearchField.superclass.onTriggerClick.call(this);
        }
    },


    /**
     * The Search button
     */
    onTrigger2Click : function() {
        this.onTriggerClick();
    },

    /**
     * The clear icon
     */
    onTrigger1Click : function() {
        if (this.hiddenField) {
            this.hiddenField.value = '';
        }
        this.setRawValue('');
        this.lastSelectionText = '';
        this.applyEmptyText();
        this.value = '';
        this.triggers[0].hide();
        this.fireEvent('clear', this);
    }
});


// We register this new component in ExtJS
Ext.reg('searchfield', Ext.Ice.SearchField);

No comments:

Post a Comment