PDA

View Full Version : model with nested object



Ghurdyl
19 Aug 2011, 5:36 AM
Hello,

Is it possible to crate an Ext.Model subclass that would have nested objects but not a collection of objects ?

Example : an "contact" would have one single nested "address"
contacts : [{
firstName: 'foo',
lastName: 'bar',
address: {
street: 'Bar lane'
zip: '1234'
city: 'Foo-city'
}
}];
I need to create a grid (so a store) that would be able to read such formated data.
Ext3 was able to do it but can't find a way to do in in 4.0

Tanks for any help.

skirtle
22 Aug 2011, 2:01 PM
Not 100% sure I've understood your question correctly but here are 2 ways of doing what I think you're trying to do.

Firstly, my JSON response looks like this:


[
{
"id": 1,
"name": "Tom",
"address": {
"city": "London"
}
},
...
]

You could load this in a manner very similar to ExtJS 3:


new Ext.data.JsonStore({
autoLoad: true,
fields: [
'id',
'name',
{name: 'city', mapping: 'address.city'}
],
proxy: {
type: 'ajax',
url: 'data/nested.json'
}
});

Alternatively, if you wanted to give it more of an ExtJS 4 feel you could throw in an explicit model creation:


Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
'id',
'name',
{name: 'city', mapping: 'address.city'}
],
proxy: {
type: 'ajax',
url: 'data/nested.json',
reader: {
type: 'json'
}
}
});

new Ext.data.Store({
autoLoad: true,
model: 'User'
});

I don't know of any way to split this up into 2 models (user and address) and create a 1-1 relationship. The 2 possibilities I describe above both work nicely with a grid, as requested.

Ghurdyl
22 Aug 2011, 11:08 PM
Thanks skirtle,

It does the trick, though it's not really perfect as somehow, it forces to flatten the object.

skirtle
22 Aug 2011, 11:34 PM
As far as I can tell the association stuff doesn't explicitly support 1-1 relationships. For a 1-many relationship it isn't entirely clear what the natural rendering of many values in a grid cell would be, so I guess it makes sense not to allow it.

That said, having given this a little more thought, it occurs to me that you could use the associations if you write a custom renderer function. The renderer has access to the whole record, so presumably you could just use that to grab the address and render it as you see fit.

Ghurdyl
23 Aug 2011, 7:00 AM
Yes indeed, custom renderer is an option too.

The last point I'll need to investigate is which option is the most suitable in case of sorting.
Especially remote sorting, as I expect to retrieve (server side) a parameter like
{sort: "address.locality", direction: "ASC"}

I'll update this thread when I'll know :)

Right now I am struggling with some other component.