Wednesday, 13 November 2013

How to get all store records in Sencha Touch 2

In Sencha Touch 2, getData() method is used  to get all the model records instance from the store. Let's see the implementation with an example

Create a Model

First, let's create a model class with name UserModel with these fields Name, DateOfBirth and Age.

Ext.define('MyApp.model.UserModel', {
    extend: 'Ext.data.Model',
    alias: 'model.UserModel',

    config: {

        fields: [{
            name: 'Name',
            type: 'string'
        }, {
            name: 'DateOfBirth',
            type: 'string'
        }, {
            name: 'Age',
            type: 'string'
        }]
    }
});

Create a Store 

Now, we are going to create a store with class name UserStore and associate the above created UserModel class to the store using model configuration. Proxy type configuration will be set to localstorage which will store the data in the browser Local Storage using HTML5 LocalStorageAPI.

Ext.define('MyApp.store.UserStore', {
    extend: 'Ext.data.Store',
    alias: 'store.UserStore',

    requires: [
        'MyApp.model.UserModel'
    ],

    config: {
        model: 'MyApp.model.UserModel',
        storeId: 'UserStore',
        proxy: {
            type: 'localstorage'
        }
    }
});

Access all model records from the Store 

First, we are going to insert data to the store using add() method, which will accept model instance as the parameter.

var UserStore = Ext.getStore('UserStore');

 UserStore.load();

 UserStore.add({
     Name: 'A Suresh',
     DateOfBirth: '21-07-1981',
     Age: '31'
 });

 UserStore.add({
     Name: 'Ramesh',
     DateOfBirth: '21-04-1981',
     Age: '25'
 });

 UserStore.add({
     Name: 'Raju',
     DateOfBirth: '01-04-1981',
     Age: '29'
 });

 UserStore.sync();

Now, in order to get all the added model records from the store, we are going to use getData() method. This method will return the array of model record instances.

var modelData = UserStore.getData();

Inorder to get the length of the store, you can use the below code

var dataLength = UserStore.getData().length;

In order to access the model record by index value. the below code will return the first record from the store.

var modelRecord = UserStore.getData().getAt(0);

Hope, you enjoyed this Post.

No comments:

Post a Comment