Search code examples
extjs4

ExtJS bidirectional complex data binding Form


give a JSON data like this

{ name: { firstname: 'First Name', lastname: 'Last Name' } }

I can model use model mapping

fields: [
  {Name: 'firstname', mapping: 'name.firstname'},
  {Name: 'lastname', mapping: 'name.lastname'}
]

It allow us to load the data into form like this

First Name: [ First Name ]

Last Name: [ Last Name ]

However when we submit the form Ext serialize the content as

{ "firstname": "New first name", "lastname": "New last name"}  
// instead of 
{ "name": { "firstname": "...", "lastname": "..."} }

Is there anyway I can tell Ext to serialize the object back to the nest form, regards.

P.S: my Edit.js taking from Ext MVC application guide http://docs.sencha.com/extjs/4.2.2/#!/guide/application_architecture


Solution

  • You need to configure two properties in your json writer. You need to set nameProperty: 'mapping', and expandData: true. For example, if you are configuring this writer in the proxy in your model, it would look like this:

    proxy: {
        // other proxy config...
        writer: {
            type: 'json',
            nameProperty: 'mapping',
            expandData: true
        }
    }
    

    nameProperty determines where the property name for each field comes from: either the name property or the mapping property. So, using your example, this will produce an object like this:

    { 'name.firstname': 'New first name', 'name.lastname': 'New last name' }
    

    This is quite what you want yet, and that is where expandData comes in. This tells it to expand those dot-delimited properties in the example above, and create nested objects.

    { 'name': { 'firstname': 'New first name', 'lastname': 'New last name' } }
    

    Docs: