PDA

View Full Version : How To Save A Record with 'hasMany' Association?



billtricarico
3 Jan 2012, 10:55 PM
What is the correct way to save a model instance with 'hasMany' ?


If I have these models:



Ext.define('Application.model.Order', {
extend: 'Ext.data.Model',


fields: [
{ name: 'orderId', type: 'int' },
{ name: 'customerId', type: 'int' }
],


hasMany: 'orderItems',


proxy: {
type: 'ajax',
url : 'Order',
reader: {
type: 'json',
root: 'results'
}
}
});




Ext.define('Application.model.OrderItem', {
extend: 'Ext.data.Model',


fields: [
{ name: 'orderItemId', type: 'int' },
{ name: 'item', type: 'string' },
{ name: 'cost', type: 'float' }
],


belongsTo: 'Order',


proxy: {
type: 'ajax',
url : 'OrderItem',
reader: {
type: 'json',
root: 'results'
}
}
});




and I create an order like this:



var newOrder = new Application.model.Order
({
orderId : 1,
customerId : 100,
orderItems : []
});




I tried creating an order item and pushing it into the orderItems array:



var newOrderItem = new Application.model.OrderItem
({
orderItemId : 999,
item : 'Stuff',
cost : 49.99
});

newOrder.data.orderItems.push(newOrderItem);


This order item does not exist in the payload when sent to the server. How can I make that work?


Also, if both of the models have proxies, will that cause any problems when I save an order?


Thanks.

el_chief
3 Jan 2012, 11:04 PM
add this to your model's proxy definition, assuming you are using JSON:



writer:new Ext.data.JsonWriter({
getRecordData:function(record){
Ext.apply(record.data, record.getAssociatedData());
return record.data;
}
})

billtricarico
4 Jan 2012, 8:27 PM
That gives me something to go on. However, when I try record.getAssociatedData(), all I get is an Object that has a bunch of functions and my hasMany data is not there.

Seeing as record.getAssociatedData() is used to get the data, how do you put the data? In other words, is there some kind of setAssociatedData()? Nothing like that exists on Ext.data.Model.

Thanks.