ExtJS 5.1 won't send nested JSON object to my server

I am trying to send a nested JSON object to my server through my store's proxy. I am using ExtJS 5.1 and in the code below I have used an attribute hasMany

to indicate the nested JSON model.

Ext.define('MyApp.model.PersonStore',{
     extend: 'Ext.data.Store',
     model: 'MyApp.model.Person',
     storeId: 'PersonStore',
     proxy: {
        type: 'ajax', 
        url: 'http://localhost:80/index.php?person=create', 
        reader: {
           type: 'json'
        },
        writer: {
           type: 'json'
        }
    }
});

Ext.define('MyApp.model.Person',{
     extend: 'Ext.data.Model',
     idProperty: 'id',
     fields: [
         {name: 'id', type: 'int'},
         {name: 'name', type: 'string'},
         {name: 'age', type: 'int'},
     ],
     hasMany: {
         model: 'MyApp.model.Item',
         name: 'items',
         associationKey: 'items'    
     } 
});

Ext.define('MyApp.model.Item',{
     extend: 'Ext.data.Model', 
     fields: [
         {
             name: 'id', 
             type: 'int'
         },
         {
             name: 'itemType', 
             type: 'string'
         }
     ],
     belongsTo: 'MyApp.model.Person'     
});

      

Then in my controller, when creating a new Person, I do this:

var store = grid.getStore();
store.add({name: 'Steve', age: '50'});
var lastInsertedPerson = store.last();
var items = lastInsertedPerson.items();
items.add({itemType: 'item1'}); 
items.add({itemType: 'item2'}); 

store.sync();

      

Then the POST request is sent in this format:

{"id":"MyApp.model.Person-1", "name":"Steve", "age":"50"}

      

but I expect it to be:

{"id":"MyApp.model.Person-1", "name":"Steve", "age":"50", "items":[{"itemType":"item1"}, {"itemType":"item2"}]}

      

So why doesn't the json object in the POST request contain the nested object Item

?

+3


source to share


1 answer


For the nested data to be present in the post object, you need to set the configuration in the proxy record object of the parent model. So if you change the model Person

to look like the code below, the nested objects should get through:

Ext.define('MyApp.model.Person',{
    extend: 'Ext.data.Model',
    idProperty: 'id',
    fields: [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'age', type: 'int'},
    ],
    hasMany: {
        model: 'MyApp.model.Item',
        name: 'items',
        associationKey: 'items'
    },
    proxy: {
        url: '/url/to/your/backend/service',
        writer: {
            type: 'json',
            allDataOptions: {
                associated: true
            }
        }
    }
});

      



Note that the script has configuration partialDataOptions

, so if you want nested data to go through PUT, config must be set there as well associated

. For more information on write configuration parameters, see the Ext Docs .

0


source







All Articles