Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Association Sample in extjs 4.2:

Tags:

extjs

Can any one please point me to a working example of association (with hasMany and belongsTo) in ExtJS. Please don't point me to Sencha docs or any examples related to Sencha because I had tried almost everything but none of them works...

like image 370
CARTIC Avatar asked May 10 '13 12:05

CARTIC


1 Answers

Running sample (turn on your browser console):

http://jsfiddle.net/4TSDu/52/

Ext.define('My.model.Author', {
    extend:'Ext.data.Model',
    fields:[
        'name'
    ]
});

Ext.define('My.model.Comment', {
    extend:'Ext.data.Model',
    fields:[
        'emailAddress',
        'body'
    ]
});

Ext.define('My.model.BlogPost', {
    extend:'Ext.data.Model',
    fields:[
        'title',
        'body'
    ], 
     belongsTo:[
        {
            name:'author',
            instanceName:'author',
            model:'My.model.Author',
            getterName:'getAuthor',
            setterName:'setAuthor',
            associationKey:'author'
        }
    ], 
    hasMany:[
        {
            name:'comments',
            model:'My.model.Comment',
            associationKey:'comments'
        }
    ], 
    proxy:{
        type:'ajax',
        url:'https://dl.dropboxusercontent.com/u/1015920/Ext/blog-posts.json',
        reader:{
            type:'json',
            root:'data'
        }
    }
});

My.model.BlogPost.load(1, {

    success:function(record, operation){

        console.log(record.get('title')); // "some title"

        console.log(record.getAuthor().get('name')); // "neil"

        console.log(record.comments().getCount()); // 2

    }
});

Read more here:

http://extjs-tutorials.blogspot.ca/2012/05/extjs-belongsto-association-rules.html

http://extjs-tutorials.blogspot.ca/2012/05/extjs-hasmany-relationships-rules.html

The sample data used:

{
    "data": [
        {
            "id": 1,
            "title": "some title",
            "body": "some body",
            "author": {"id":1, "name": "neil"},
            "comments": [
                {
                    "id":55,
                    "emailAddress": "[email protected]",
                    "body": "test comment"
                },
                {
                    "id":66,
                    "emailAddress": "[email protected]",
                    "body": "another comment"
                }
            ]
        }
    ]
}
like image 64
Neil McGuigan Avatar answered Oct 21 '22 07:10

Neil McGuigan