Sencha Touch 2 Search Field Example - Filter a Data List

The search field is an extension of the text field so it automatically inherits all the functionality that a text field has. In essense it is same as a text field with just a different look and feel. You can achieve the same result using a text field. In this example we load up a list with JSON data from MySQL database using Java servlets and then use the search field to filter the list with each key stroke. This is achived by overriding the filterBy function of the store to return true or false based on our custom search criteria.

Sencha Touch Search Field Example
Sencha Touch Search Field Filter

Application starting point - index.html

<!DOCTYPE html>
<html>
<head>
<title>Sencha Touch Filter List using Search Field</title>
<link rel="stylesheet"
 href="sencha-touch/resources/css-debug/sencha-touch.css"
 type="text/css">
<style type="text/css">
.myButton {
 margin-left: 10px;
 margin-right: 10px;
 float: left;
}

.myContent {
 margin-bottom: 5px;
}
</style>
<script type="text/javascript"
 src="sencha-touch/sencha-touch-all-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>

Source for JavaScript file - app.js

Ext.Loader.setConfig({ 
 enabled: true 
});

Ext.application({
    
 name: 'MyApp',
 appFolder: 'app',
 
 requires: [
               'MyApp.view.MainPanel',
               ], 
               
    views : ['MainPanel'],           
    controllers: ['SearchDemo'],
    
    launch: function() {
     console.log('Application launch');
     Ext.create('Ext.Container', {
      fullscreen: true,
      layout: 'vbox',
         items: [{
          flex: 1,
          xtype: 'mainPanel'
            }]
     });
    }
    
});

Source for Model Object - Country.js

Ext.define('MyApp.model.Country', {
    extend: 'Ext.data.Model',
    config: {
     fields: [
              'code',
              'name',
              'continent',
              'region',
              'lifeExpectancy',
              'gnp'
              ]
    }
});

Source for Data Store Object - Countries.js

Ext.define('MyApp.store.Countries', {
    extend: 'Ext.data.Store',
    
    config: {
     model: 'MyApp.model.Country',
     autoLoad: true,
     
     proxy: {
         type: 'ajax',
         url: 'CountryServlet',
         reader: {
             type: 'json',
             totalProperty: 'totalCount',
             rootProperty: 'countries',
             successProperty: 'success'
         },
   }
    }
});

Source for List View with Search Field - MainPanel.js

Ext.define('MyApp.view.MainPanel', {
    extend: 'Ext.dataview.List',
    alias : 'widget.mainPanel',
    
    config: {
     store : 'Countries',
     
     

     itemTpl:  '<div class="myContent">'+ 
         '<div>Country is <b>{name}</b></div>' +
         '<div>Continent: <b>{continent}</b> Region: <b>{region}</b></div>' +
         '</div>',
    
     emptyText: '<div class="myContent">No Matching Countries</div>',
         
  items: [
                 {
                     xtype: 'toolbar',
                     docked: 'top',
 
                     items: [
                         {
                             xtype: 'searchfield',
                             placeHolder: 'Search...',
                             itemId: 'searchBox'
                         }
                     ]
                 }
             ]   
    
    } 
});

Source for Application Controller - SearchDemo.js

Ext.define('MyApp.controller.SearchDemo', {
 extend : 'Ext.app.Controller',

 config: {
  profile: Ext.os.deviceType.toLowerCase(),
  stores : ['Countries'],
  models : ['Country'],
  refs: {
   myContainer: 'mainPanel'
  },
  control: {
   'mainPanel': {
    activate: 'onActivate'
   },
   'mainPanel searchfield[itemId=searchBox]' : {
    clearicontap : 'onClearSearch',
    keyup: 'onSearchKeyUp'
   }
  }  

 },

 onActivate: function() {
  console.log('Main container is active');
 },

 onSearchKeyUp: function(searchField) {
  queryString = searchField.getValue();
  console.log(this,'Please search by: ' + queryString);

  var store = Ext.getStore('Countries');
  store.clearFilter();

  if(queryString){
   var thisRegEx = new RegExp(queryString, "i");
   store.filterBy(function(record) {
    if (thisRegEx.test(record.get('name')) ||
      thisRegEx.test(record.get('continent')) ||
      thisRegEx.test(record.get('region'))) {
     return true;
    };
    return false;
   });
  }

 },

 onClearSearch: function() {
  console.log('Clear icon is tapped');
  var store = Ext.getStore('Countries');
  store.clearFilter();
 },

 init: function() {
  console.log('Controller initialized');
 }

});

Click here to view the backend Java Servlet coding

References