PDA

View Full Version : Json writer - restore field mapping



dcavin
21 Feb 2012, 7:58 PM
I'm having trouble getting the json writer to 'undo' the mapping done in the model when I post the data back to the server.

This is how the data loads from the server initially:

[{
"fields": {
"data1": 123,
"data2": "abc"
},
"attributes": { }
}, {
"fields": {
"data1": 456,
"data2": "def"
},
"attributes": { }
}]


The fields on my model look something like this:

fields: [{
name: 'data1',
mapping: 'fields.data1'
}, {
name: 'data2',
mapping: 'fields.data2'
}, {
name: 'attributes'
}]

The problem is, I can't figure out how to set up the json writer to recreate the original json format when posting the model data back to the server. Setting the nameProperty to 'mapping' results in json using dot notation, which I don't want:

{
"fields.data1": 456,
"fields.data2": "def",
"attributes": { }
}

I can't find any indication that what I want to do is possible but I thought I'd ask anyway.

EDIT:
I've come up with a solution that does what I need, by overriding JsonWriter's writeRecords method. Is there any better way to do this?


Ext.override(Ext.data.writer.Json, {
writeRecords: function(request, data) {
for (var i = 0; i < data.length; i++) {
for (var j in data[i]) {
var d = j.indexOf('.');
if (data[i].hasOwnProperty(j) && d != -1) {
var k = j.substring(0,d);
data[i][k] = data[i][k] || {};
data[i][k][j.substring(d+1)] = data[i][j];
delete data[i][j];
}
}
}
return this.callOverridden(arguments);
}
});


Thanks!

-David

mitchellsimoens
21 Feb 2012, 8:08 PM
What does your store look like?

dcavin
21 Feb 2012, 8:18 PM
This is how the store is currently set up:

Ext.define('Scout.store.AssetViews', {
extend: 'Ext.data.Store',
model: 'Scout.model.AssetView',


constructor: function (cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'AssetViews',
proxy: {
type: 'rest',
url: '/rest/service/url',
reader: {
type: 'json',
messageProperty: 'Message',
root: 'Result',
successProperty: 'Success',
totalProperty: 'Count'
},
writer: {
type: 'json',
nameProperty: 'mapping',
allowSingle: false
}
}
}, cfg)]);
}
});

srxx123
24 Aug 2012, 4:36 AM
Hi,
any chance to get the writer respecting the mapping of the model?
Thank you

sriram139
24 Sep 2013, 1:31 PM
http://docs-origin.sencha.com/extjs/4.2.1/#!/api/Ext.data.writer.Json-cfg-expandData

Unfortunately, it didnt work even with this config. :(