PDA

View Full Version : Asynchronous hasMany



Araberen
11 Dec 2011, 12:23 PM
Hi,

I have 2 models:
A model for a 'User' and a model for a 'Group' which is made of a hasMany association with the 'User' model.


Ext.define('App.model.User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id' , type: 'int' },
{ name: 'email' , type: 'string' },
{ name: 'firstName', type: 'string' },
{ name: 'lastName' , type: 'string' }
],
proxy: {
type: 'rest',
url : '/rest/user',
reader: {
type: 'json',
root: 'data'
}
}
})


Ext.define('App.model.Group', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id' , type: 'int' },
{ name: 'name' , type: 'string' },
{ name: 'countOfUsers', type: 'int' }
],
hasMany: { name: 'users', model: 'App.model.User' },
proxy: {
type: 'rest',
url : '/rest/group',
reader: {
type: 'json',
root: 'data'
}
}
})

My web service for the group only gives the id, the name and the count of users for the group. No user are sent.
So what I want is :

var g = Ext.create('App.model.Group', { id:1, name:'Groupe A' });
var users = g.users(); // I want this to auto make a request
// because users.load() will require /rest/user?id=1 instead of requiring /rest/group?id=1

Any idea or alternative?

Araberen
12 Dec 2011, 12:43 AM
I finally found how to do it. Here is the key function:


function(grid, record) {
var me = this;

var groupId = record.get('id');
// The next line will request /rest/group/123 if groupId equals to 123.
Ext.ModelManager.getModel('LAD.model.Group').load(groupId, {
success: function(group) {
var users = group.users(); // hasMany is useful here!
me.getGroupUser().getStore().loadRecords(users.getRange(0, users.getCount()),{ addRecords: false });
},
failure: function() {

}
});
}


Of course, it supposes that:
/rest/group gives all the groups with their users
/rest/group/<id> give just the group with id <id> and all its users.