Sencha ExtJS Store “findRecord” query examples

Here are a few short examples of how to find an object in a Sencha Store (ExtJS or Sencha Touch).

As a first example, imagine that you have a Store of users, and want to find a user with the first name of “Alvin”. Assuming that your user model has a field named firstName, your query would look like this:

var user = usersStore.findRecord('firstName', 'Alvin');

After this query you can use the user object just as though you had created it by hand. (The object returned is a Model instance.)

Another example

As another short example, I’m working on a project where I need to find the id field for a project, given the project’s name, and used this code to search my project store:

// get the projectId from the projectName
getProjectId: function(projectName) {
    var projectsStore = this.getProjectsStore();
    var project = projectsStore.findRecord('name', projectName);
    return project.get('id');
},

Each project has a name field, so I search by that field, get a project object, then return the value of the id field. This is a simple application where I’m very sure that I’ll find a valid project object, but in more robust code you may want to check to make sure the object returned from the store is valid.

FWIW, my Project model looks like this:

Ext.define('Focus.model.Project', {
    extend: 'Ext.data.Model',
    idProperty: 'id',
    fields: [
        { name: 'id' },
        { name: 'userId' },
        { name: 'name' },
        { name: 'displayOrder' },
        { name: 'dateCreated' }
    ]
});

Limits

The Sencha Store documentation details a few limits of the findRecord method:

  • Finds the first matching Record in the store.
  • When store is filtered, finds records only within filter.
  • If this store is buffered, this can ONLY find records which happen to be cached in the page cache.

Documentation

The Store documentation states that findRecord takes these parameters, where only the first two are required:

  • fieldName
  • value
  • startIndex
  • anyMatch
  • caseSensitive
  • exactMatch

See the Store documentation for more details.