PDA

View Full Version : Load nested data on record save



abhijit
12 Dec 2012, 1:32 AM
I want to create a 'details' record on the server and send it back when the 'master' is created.

The 'details' record is NOT created in the front. Instead the 'master' record is created and posted.
When the response is received the 'details' record is also part of the response.

I have set up the associations between the 'master' and the 'details'. However, the 'master' does not read the 'details' array in the response.


Master model -


Ext.define('App.model.Master', {
extend : 'Ext.data.Model'

,fields : [
{ name : 'master_name', type : 'string' },
{ name : 'id', type : 'int'}
]
,proxy : {
type : 'rest',
url : '/master',
reader : {
type : 'json',
root : 'masters'
}
}
,associations : [{
type : 'hasMany'
id : 'id',
foreignKey : 'master_id',
associationKey : 'details',
name : 'details',
model : 'App.model.Detail',
}]
});

Master Store -


Ext.define('App.store.Master', {

extend : 'ScaleApp.store.Store'
,model : 'App.model.Master'
});


Detail model -


Ext.define('App.model.Detail', {
extend : 'Ext.data.Model'
fields : [
{ name : 'detail_name', type : 'string' },
{ name : 'id', type : 'int' },
{name : 'master_id', type : 'string'}
]
});


I'm adding the record like this -


var master_record = new App.model.Master({
master_name : 'aaa'
});
var store = Ext.StoreMgr.get('Master');
store.add(master_record);
store.sync();


The response object I get back is -


{
success : true,
masters : {
master_name : 'aaa',
id : 1,
details : [
{
detail_name : 'bbb',
id : 11,
master_id : 1
}
]
}
}


I was expecting that the 'record.details()' would give me the one record that came back on adding of the Master, but I get nothing.

However, if I reload the store, I'm able to get the data correctly.

I need to be able to read the nested response on Store.add() as well.

Any suggestions?

Thanks in advance.

mitchellsimoens
14 Dec 2012, 6:01 AM
Associated data needs to be run through the reader in order to work. In these cases they are not run through the reader properly or at all for associations to work.

abhijit
15 Dec 2012, 5:07 AM
Thanks Mitchell, I got that. Is there any workaround that you can suggest?

Currently, I'm doing this -



Ext.StoreMgr.get('Master').on({
write: function(st, operation){
if (operation.action == 'create'){
var resp_obj = Ext.decode(operation.response.responseText);

if (resp_obj.masters.details){
var rec = operation.records[0];
var details_store = rec.details();
var details_records = resp_obj.masters.details;

details_store.add(details_records);
}
}
}
});


Is there a better way?