Search code examples
jsonextjsmodelassociationsstore

Extjs simple model and store


I have a simple model, let's say:

Ext.define('UserModel', {
    extend: 'Ext.data.Model',

    fields: [
        {name: 'firstname',    type: 'string'},
        {name: 'lastname',     type: 'string'}
    ]
});

And a json file that looks like this:

{  
"DatabaseInJSON": {
    "Users": [
      {
        "KeyFirstName": "John",
        "KeyLastName": "Doe"
      },{
        "KeyFirstName": "James",
        "KeyLastName": "Howlett"
      }
    ],
    "OtherStuffWeDontCareAbout": [
        ...
    ]
  }
}

My question is: If I create a store like this, how can i map the attribute "firstname" from my model to "KeyFirstName" from my json ?

Ext.define('my.custom.Store', {
    extend: 'Ext.data.Store',

    model: 'UserModel',

    proxy: {
        type: 'ajax',
        url: 'path/to/my/file.json',
        reader: {
            type: 'json',
            rootProperty: 'DatabaseInJSON'
        }
    }
});

Solution

  • You need to either employ mapping or a convert function

    Have a look at the demo here which demonstrates both in action.

    For the sake of the demo I turned your store into a memory proxy store and you are I presume also accessing your rootProperty wrong as it should be rootProperty: 'DatabaseInJSON.Users'

    Code:

    Ext.application({
        name: 'Fiddle',
    
        launch: function() {
    
            myData = {
                "DatabaseInJSON": {
                    "Users": [{
                        "KeyFirstName": "John",
                        "KeyLastName": "Doe"
                    }, {
                        "KeyFirstName": "James",
                        "KeyLastName": "Howlett"
                    }],
                    "OtherStuffWeDontCareAbout": {}
                }
            };
    
    
            Ext.define('UserModel', {
                extend: 'Ext.data.Model',
    
                fields: [{
                    name: 'firstname',
                    mapping: 'KeyFirstName',
                    type: 'string'
                }, {
                    name: 'lastname',
                    convert: function(v, record) {
                        return record.data.KeyLastName;
                    },
                    type: 'string'
                }]
            });
    
            Ext.define('my.custom.Store', {
                extend: 'Ext.data.Store',
    
                model: 'UserModel',
    
                proxy: {
                    type: 'memory',
                    reader: {
                        type: 'json',
                        rootProperty: 'DatabaseInJSON.Users'
                    }
                }
            });
    
            myStore = Ext.create('my.custom.Store', {
                data: myData
            });
            console.log(myStore.getRange());
        }
    });