Skip to content

Monthly Archives: April 2011

EXTJS – JsonWriter not respecting DateFormat used with JsonReader

A screenshot of the Ext 2.0 Web Desktop Sample App

Recently while working on a project that used Extjs as the front-end to a MySQL application, we came across an interesting issue with Extjs’s JsonStore.  The JsonStore automatically creates a Jsonreader that is used to map data coming from the MySQL application to the Extjs front-end.  The JsonReader has an optional dateFormat config property which allows the format of the incoming data to be read properly using the format delivered from MySQL.  While using the JsonWriter to update records from a EditorGrid, we noticed that the format that was sent back from the JsonWriter was using Extjs’s default dateFormat (03-04-2011T00:00:00).

It was that the JsonWriter was not respecting the dateFormat defined when mapping the data using JsonReader.  There would appear to be multiple hacks that could be used to fix, such as adding a Listener before the update that would modify the datefield, however we came across this little bit of code that works wonders.  This code will over-ride the default DataWriter class to use the dateFormat property defined in the JsonStore Field mappings.

//This over-ride fixes JsonWriter not using the JsonReader dateFormat when writing

Ext.override(Ext.data.DataWriter, { toHash : function(rec) {
var map = rec.fields.map,
data = {},
raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
m;

Ext.iterate(raw, function(prop, value){
if((m = map[prop])){
var key = m.mapping ? m.mapping : m.name;
if (m.dateFormat && Ext.isDate(value)) {
data[key] = value.format(m.dateFormat);
} else {
data[key] = value;
}
}
});
// we don't want to write Ext auto-generated id to hash. Careful not to remove it on Models not having auto-increment pk though.
// We can tell its not auto-increment if the user defined a DataReader field for it *and* that field's value is non-empty.
// we could also do a RegExp here for the Ext.data.Record AUTO_ID prefix.
if (rec.phantom) {
if (rec.fields.containsKey(this.meta.idProperty) && Ext.isEmpty(rec.data[this.meta.idProperty])) {
delete data[this.meta.idProperty];
}
} else {
data[this.meta.idProperty] = rec.id
}
return data;
}
});

Related articles

Visitor Trackingdata recovery softwareforexbest forex broker