Wednesday, 2 July 2014

Extjs4 : Converting JSON Object into model

ExtJS provides getData(true) method on model to convert model object into JSON Object including associations. But other way is not a straight forward thing in ExtJS4. If you have JSON and want to convert into model, one dirty way could be create a store with memory proxy, input JSON object as data object and access first record in the store. But this method is not always fruitful. If your JSON has associated data, this method will not work properly. Especially in case of hasOne association case, it never creates *HasOneInstance objects using this method.

I found similar API in Sencha touch 2.2.1 and modified a bit to make it work in ExtJS 4.2.1

  • Write following functions in ExtJS model.
  • Create a model and use setData(JSON Object)
  • It returns model with populated data along with the hasMany, hasOne associations. 
  • setData : function(rawData) {
    var me = this;
    var fields = me.fields.items;
    var ln = fields.length;
    var isArray = Ext.isArray(rawData);
    var data = me.data = {};
    var i;
    var field;
    var name;
    var value;
    var convert;
    var id;
    if (!rawData) {
    return me;
    }
    for (i = 0; i < ln; i++) {
    field = fields[i];
    name = field.name;
    convert = field.convert;
    if (isArray) {
    value = rawData[i];
    } else {
    value = rawData[name];
    if (typeof value == 'undefined') {
    value = field.defaultValue;
    }
    }
    if (convert) {
    value = field.convert(value, me);
    }
    data[name] = value;
    }
    id = me.getId();
    if (me.associations.length) {
    me.handleInlineAssociationData(rawData);
    }
    return me;
    },
    handleInlineAssociationData : function(data) {
    var associations = this.associations.items;
    var ln = associations.length;
    var i;
    var association;
    var associationData;
    var reader;
    var proxy;
    varassociationKey;
    data = Ext.apply({}, data, this.raw);
    for (i = 0; i < ln; i++) {
    association = associations[i];
    associationKey = association.associatedKey;
    associationData = data[associationKey];
    if (associationData) {
    reader = association.getReader();
    if (!reader) {
    proxy = association.associatedModel.getProxy();
    if (proxy) {
    reader = proxy.getReader();
    } else {
    reader = new Ext.data.JsonReader({
    model : association.getAssociatedModel()
    });
    }
    }
    association.read(this, reader, associationData);
    }
    }
    }
    Source can be found @https://github.com/Balagangadhar/ExtJS4-Misc/blob/master/ExtJS4JsonObjectToModel.js


No comments:

Post a Comment