Thursday, June 6, 2013

ExtJS : How to make combobox perform "Contains"/LIKE search

Hi,

I am a software engineer working mostly on Java, Javascript, Struts, Spring and MySQL.
Recently I have started working on ExtJS and I found it really interesting and exciting.
It surely is a great way to develop webapps with rich and stable GUI.

Here I will be sharing some of the daily learnings, tips&tricks, solutions to issues that I face every day.
Hope this helps someone..

So today I will start with something small but very useful functionality in ExtJs.
How to get a '%LIKE%' search functionality in a textbox or a combobox?

Lets start with creating a simple combobox in ExtJs

 
// The data store containing the list of states
var cars = Ext.create('Ext.data.Store', {
    fields: ['key', 'name'],
    data: [{
        "key": "Benz",
            "name": "Mercedes-Benz"
    }, {
        "key": "Audi",
            "name": "Audi"
    }, {
        "key": "Ferrari",
            "name": "Ferrari"
    }, {
        "key": "Prius",
            "name": "Prius"
    }, {
        "key": "Lamborghini",
            "name": "Lamborghini"
    }, {
        "key": "BMW",
            "name": "BMW"
    }
    //...
    ]
});

// Create the combo box, attached to the states data store
Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose Car',
    store: cars , //store name defined above
    queryMode: 'local',
    displayField: 'name', // value field
    valueField: 'key', //key field
    renderTo: Ext.getBody() //render on the page
});

So this will create a simple dropdown on the screen.
Notice we two properties in the above configuration:
1. typeAhead: true and 2. editable: true

These properties will by default provide search functionality on the data of the combobox as you start typing.
But this will do a "Starts With" search instead of a "Contains" or "LIKE" search.

To do that, do the following:

 
listeners: {
        beforequery: function (record) {
            record.query = new RegExp(record.query, 'i');
            record.forceAll = true;
        }
    } 

Just add the above listeners having 'beforequery' event to your dropdown.
That's it!! Your dropdown will do a "Contains" search.

Now last step, converting the combobox into a texbox

 hideTrigger: true  

Now it's a textbox with search functionality.

JSFiddle Demo

8 comments:

  1. Does this work with Ext 3.3.1?

    ReplyDelete
    Replies
    1. To be frank I havent used Ext 3.3.1
      But I tried using Ext3.x in the JSFiddle demo. And unfortunately the combo box disappeared.
      But this worked in all Ext4.x

      Delete
  2. works for me, I added record.combo.store.clearFilter() as I populate the store as the user types

    ReplyDelete
  3. It worked for me too. thanks a lot :)

    ReplyDelete
  4. for extjs 4.2.1, combo comes with anyMatch config

    ReplyDelete
  5. JS Fiddle for anyone who has trouble with the linked one: http://jsfiddle.net/x8tfsc3g/1/

    ReplyDelete