Hi,
for a project of mine, a json enabled store is used to communicate with a restfull api (cakePHP).
The json it receives when loading data is the following (very simple):
[{"User":{"id":"1","username":"user","password":"pass","created":null,"modified":null}},
{"User":{"id":"3","username":"user2","password":"pass","created":null,"modified":null}}]
As u can see it is nested data, with User as a key.
This is default cakePHP behavior, and I haven't been able to change this in an easy way.
I read the documentation regarding json readers and it states you can provide a "record" name where the record data itself can be found at. But when I set "User" as the record, nothing happens.
I couldnt figure out why this isnt working so I created a "fix". See the code below:
I've read a lot of posts on this subject but couldn't find the solution, so I've come up with the following. I hope somebody here can give me feedback on this, because I'm new at sencha and maybe the change has undesired sideeffects. I haven't discovered any so far though.
Basically, what I do is override the readRecords function of the jsonreader to loop through the fetched and parsed records, building a new array of "User" objects in the process. As you can see it uses the record variable of the jsonreader to verify which object it should fetch.
Code:
Ext.override(Ext.data.JsonReader, {
readRecords: function(data) {
//this has to be before the call to super because we use the meta data in the superclass readRecords
if (data.metaData) {
this.onMetaChange(data.metaData);
}
/**
* DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead
* @property jsonData
* @type Mixed
*/
this.jsonData = data;
// Loop through data, using "record" to create a a new data object
var newData = new Array();
var record = this.record;
Ext.each(data, function(d,index){
newData[index] = (eval('d.'+record));
});
return Ext.data.JsonReader.superclass.readRecords.call(this,newData);
}
});
app.stores.users = new Ext.data.Store({
model: 'app.models.User',
proxy: {
type: 'rest',
url : '/api/users.json',
reader: {
type : 'json',
root: '',
record: 'User'
}
}
});
I hope this helps someone else. It's pretty simple. I can imagine one would want to get other nested data, but this was out of my scope.
If there's a better solution, please let me know. Feel free to copy/edit the code above.
Kind regards,
Jochem