0
votes

So, I have a problem using Sencha ExtJs 4.1 Associations.

I have something like:

Models

Ext.define('Tpl.model.User', {
    extend: 'Ext.data.Model',
    requires: ['Tpl.model.PostTemplate'],
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' },
        { name: 'postTemplate', type: 'int' }
    ],
    associations: [
        { type: 'belongsTo', name: 'postTemplate', model:'Tpl.model.PostTemplate', associationKey: 'postTemplate', primaryKey: 'id', foreignKey: 'postTemplate' }
    ]
});

and

Ext.define('Tpl.model.PostTemplate', {
    extend: 'Ext.data.Model',

    fields: [
        { name: 'id', type: 'int' },
        { name: 'blah', type: 'string' }
    ],

    associations: [
        { type: 'hasMany', model: 'Tpl.model.User' }
    ]

});

Stores

Ext.define('Tpl.store.Users', {
    extend: 'Ext.data.Store',
    model: 'Tpl.model.User',
    autoLoad: true,
    proxy: {
        type: 'rest',
        url: '../users',
        reader: {
            type: 'json',
            root: ''
        },
        writer: {
            type: 'json'
        }
    }
});

Ext.define('Tpl.store.PostTemplate', {
    extend: 'Ext.data.Store',
    model: 'Tpl.model.PostTemplate',
    autoLoad: true,
    proxy: {
        type: 'rest',
        //appendId: true,
        url: '../postTemplates/',
        reader: {
            type: 'json',
            root: ''
        },
        writer: {
            type: 'json'
        }
    }
});

The problem is that I'm getting a POST like this:

{
    "postTemplate": 1,
    "id": 0,
    "name": "foo"
}

But I need a POST like this:

{
    "postTemplate": {
        "id": 1,
        "blah": "foo"
    },
    "id": 0,
    "name": "bar"
}

Also, the assessor function like "setPostTemplate" doesn't exist and I think it should be created automatically.

Already tried to something like " record.data.postTemplate = (...) " but I got an infinite loop throwing an execption...

Can someone please advise? Also, if you need something else that could be useful for the answer let me know.

Thanks!

1

1 Answers

1
votes

Out of the box the Associated objects are not serialized back to the server as you expect them . This issue has been brought up many times. The best thing might be to follow this thread:

http://www.sencha.com/forum/showthread.php?141957-Saving-objects-that-are-linked-hasMany-relation-with-a-single-Store

This thread talks about overriding getRecordData in the JSON writer class.