PDA

View Full Version : Hint: Models with hasMany in Lists



NeoVanGoth
27 Oct 2010, 6:56 AM
Hi,

it took me several hours to fiddle this out.

I had a model with a hasMany association and tried to use it in a XTemplate of a list. To be precise, I had a list of persons, where every person could have many places of work and wanted to display all places below the persons name in the list.
After following the API docs and the examples for Model and XTemplate, I couldn't get it to work.

I had something like this (simplified):


Models

Ext.regModel ('PlaceOfWork', {
fields: [
{ name: 'name', type: 'string' }
],
belongsTo: 'Person'
});

Ext.regModel ('Person', {
fields: [
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' }
],
associations: [
{ type: 'hasMany', model: 'PlaceOfWork', name: 'placesOfWork' }
});

XTemplate

new Ext.Xtemplate ('<tpl for="."><div class="person">' +
' {firstname} <strong>{lastname}</strong>' +
' <tpl for="placesOfWork"><br /><small>{name}</small></tpl>' +
'</div></tpl>');

JSON Example

[{"firstname":"Foo","lastname":"Bar","placesOfWork":[{name:"Laber"},{name:"Fasel"}]}]


This produced the error "placesOfWork" is undefined. After doing some debugging, I found out that the template doesn't receive all keys in my JSON, but only those which are a field in the model.

So remember: When using a hasMany association, it is _required_ to add the associations name as field!



Ext.regModel ('Person', {
fields: [
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' },
{ name: 'placesOfWork', type: 'array' }
],
associations: [
{ type: 'hasMany', model: 'PlaceOfWork', name: 'placesOfWork' }
});


I think, we need a far more complete example in the docs, as XTemplate in combination with Models seem to be quite important in S/Touch.

[Edit: Typo]

edspencer
28 Oct 2010, 12:11 PM
This got a lot easier in 0.98 - I added a comment with some explanation on another thread (http://www.sencha.com/forum/showthread.php?113944-0.98-Associations&p=531702#post531702). I'm working on updating the API docs to make this clearer.

savelee
30 Jan 2011, 2:39 AM
Thanks, you made my day!

epiphanydigital
15 Jul 2011, 5:19 AM
Hi guys... this is still not very intuitive to me.

I have a models "Profiles" hasMany "Supplements". I open up my app and adding a profile works just fine, but the Supplement list tries to load the parent, "Profiles", info instead of the list of child records. That said, if I print out something like this on the Supplements list panel:

Ext.Msg.alert('Warning!','There are ' + records.length + ' records.',Ext.emptyFn);

I do get the correct number of records showing for Supplements.

Thanks in advance for your help.