How to make a store with jsonreader using metadata in Extjs 4?

3.5k views Asked by At

Is it possible to create a store that will read json, and use fields specified in the metadata in the json as a model?

I want to say something like:

var store = new Ext.data.Store({
    autoLoad: {
        params: {
            metaNeeded: true
        }
    },
    reader: new Ext.data.JsonReader({fields:[]}),
    proxy: new Ext.data.HttpProxy({
        api: {
            url: 'php/chart-data.php'
        }
    })
});

I've tried a number of combinations however I cannot seem to get it to work. I currently get the error "Cannot call method 'indexOf' of undefined". I've had others including "object has no read method".

The json I am sending is:

{
  metadata:{
    root:"rows",
    sortInfo:{
       field:"date",
       direction:"ASC"
    },
    fields:[ {
          name:"date"
       }, {
          name:"flow"
       },{
          name:"limit"
       }
    ],
    idProperty:"date"
  },
  success:true,
  rows: << snip >>
}

Is it possible to have the store's model configured by the data that it receives, so I could use the same store later with different fields (e.g. date, flow, limit and temperature)?

1

There are 1 answers

0
Matt L On

I have gotten it to work with the following:

var store = new Ext.data.Store({
    proxy: {
        type: 'ajax',
        url: 'php/chart-data2.php',
        reader: new Ext.data.JsonReader({
            fields:[]
        })
    }
});

And the php that sends the json:

'{"metaData":{
        "root":"rows",
        "fields": [
            {"name":"date",
             "type":"number", 
             "convert": function(val, rec) {
                return val*1000
            } },
            {"name":"flow"},
            {"name":"limit"}
        ]
    },
    "totalCount":'.count($chart).',
    "success":true,
    "rows":' . json_encode($chart) . '
}'

This now allows the server to specify the data (that's getting displayed in a chart), and can add in series dynamically. I don't know if it is good, but it works. I am kind of disappointed in the lack of documentation about this.