Hi,
I found an annoying bug while working on localStorage with date fields.
I have a model bound to a localstorageProxy :
Code:
Ext.define('dateTest', {
extend: 'Ext.data.Model',
idProperty: 'id',
requires: ['Ext.data.SequentialIdGenerator'],
idgen: 'sequential',
proxy : {
type: 'localstorage',
id: 'datetest'
},
fields: [{
name: 'id',
type: 'int',
useNull: true
},{
name: 'myDate',
type: 'date',
dateFormat: 'Y-m-d'
}]
});
I have a date field "myDate" with dateFormat to "Y-m-d"
I create a store with this model, and add a record to it :
Code:
var store = Ext.create('Ext.data.Store', {
model: "dateTest"
});
var test = Ext.create('dateTest', {
myDate : '2011-11-23'
});
store.add(test);
store.each(function(item){
console.log("%s : %o",item.get("id"),item.get("myDate"));
});
store.sync();
The console.log line give me something I expected (a date object) :
PHP Code:
1 : Date {Wed Nov 23 2011 00:00:00 GMT+0100 (CET)}
Now I want to load my local data, but not on the same page :
Code:
var store = Ext.create('Ext.data.Store', {
model: "dateTest"
});
store.load({
callback: function(records, operation, success){
Ext.Array.each(records,function(item){
console.log(item.get("id") + " : " + item.get("myDate"));
});
}
});
So I create a new store with my model, and try to load it.
It load well but the console.log line give me :
It fails parsing the date.
As localStorage can only use plain text , ExtJS JSON Encode each record of a store.
But my guess is that it doesn't do a special treatment on date fields, and thus store dates in the wrong format.
For my use case :
Code:
Ext.encode(Date.parseDate('2011-11-23','Y-m-d'))
Gives :
PHP Code:
"2011-11-23T00:00:00"
So when the reader try to parse the date with its configured dateFormat (mine is "Y-m-d"), it fails.
A quick workaround is to add a convert function to the field in the model :
Code:
Ext.regModel('dateTest', {
idProperty: 'id',
proxy : {
type: 'localstorage',
id: 'datetest'
},
fields: [{
name: 'id',
type: 'int',
useNull: true
},{
name: 'myDate',
type: 'date',
dateFormat: 'Y-m-d',
localDateFormat : 'Y-m-dTH:i:s',
convert : function(value, rec){
if(Ext.isEmpty(value) === true){
return null;
}
var parsedValue = Date.parseDate(value,this.dateFormat);
if(Ext.isEmpty(parsedValue) === true){
formatValue = Date.parseDate(value,this.localDateFormat);
}
return parsedValue;
}
}]
});
If the reader can't parse the date using the dateFormat, it will try with localDateFormat.
But it's still a hack and a better way to handle date fields storage would be to format the date with its dateFormat before sync.
I've set up 2 jsFiddle to reproduce the bug.
The first one (http://jsfiddle.net/8wc3y/) create and store the record, the second one (http://jsfiddle.net/XnugQ/) load the record.