How to access nested models from store in ExtJs 4

Andrey Selitsky picture Andrey Selitsky · Apr 26, 2011 · Viewed 14.8k times · Source

I just downloaded the final version of ExtJs 4 and I'm trying to implement some things using new Model approach.

For instance I have a model named SetupModel, it has 2 nested models Users, Reports. I create new store and I set the Model property of the store = SetupModel.

The question is - how can I access my nested properties after data was loaded into the store?

I need something like myStore.data.Users(), but is incorrect.

Any thoughts?

Answer

Abdel Raoof picture Abdel Raoof · Apr 27, 2011

When you define your model, you need to provide the necessary association with the nested models. Since, you have not provided your code. Here is an example:

My Product Model:

Product = Ext.define('Product',{
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'int'},
        {name: 'user_id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'price', type: 'float'}
    ],
    proxy: {
        type: 'localstorage',
        id: 'products'
    }
});

My User Model:

User = Ext.define('User',{
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id',       type: 'int'},
        {name: 'name',     type: 'string'},
        {name: 'gender',   type: 'string'},
        {name: 'username', type: 'string'}
    ],
    associations: [
        {type: 'hasMany', model: 'Product', name: 'products'}
    ],
    proxy: {
        type: 'localstorage',
        id  : 'users'
    }
});

Now, if you have a instance of User model with products. Here is how you can access the products:

var productStore = user.products();

Note that user.products() returns a Ext.data.Store. Now, you can traverse or filter or find your product record. Here is how I got my first product's name:

productStore.getAt(0).get('name');