Mike
Mike

Reputation: 109

Populate ExtJS combobox with JSON

I am using ExtJS (3) and just trying to populate a combobox/drop down using records from the database that are being queried using JSON.

Here is my JSON call:

var projectDropDown = new Ext.data.Store({
    autoLoad: true,
    url: 'dropdown.json',
    storeId: 'projectDropDown',
    idProperty: 'ProjectID',
    fields: [ 'ProjectID', 'ProjectName' ]
});

And then my combobox code:

{
    xtype: 'combo',
    id: 'ProjectName',
    fieldLabel: 'Project Name',
    valueField: 'ProjectID',
    displayField: 'ProjectName',
    store: projectDropDown,
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    emptyText:'Select a Project...',
    selectOnFocus:true
}

The JSON is returning my data like this:

[
   {
      "ProjectID":"1",
      "ProjectName":"Mike's Test Project"
   },
   {
      "ProjectID":"2",
      "ProjectName":"My Second Test Project"
   },
   {
      "ProjectID":"3",
      "ProjectName":"My Third Project"
   },
   {
      "ProjectID":"6",
      "ProjectName":"More testing from me"
   }
]

I think I am close, I just don't see what I am missing to make the connection.

Thanks for any assistance.

Upvotes: 0

Views: 7133

Answers (1)

Matt Dodge
Matt Dodge

Reputation: 11142

The first step I would do would be to output the store (or size of the store or something) to the console to see if the data is getting loaded properly into the store.

My guess would be that you need to enclose your JSON that is returned into some root object. Try giving your store a JSONReader with a root element specified like so:

var projectDropDown = new Ext.data.Store({
    autoLoad: true,
    url: 'dropdown.json',
    storeId: 'projectDropDown',
    reader: new Ext.data.JsonReader(
    {
        root: 'projects'
    }),
    idProperty: 'ProjectID',
    fields: [ 'ProjectID', 'ProjectName' ]
});

Then change the JSON returned to look like this instead

{
    "projects" : [
       {"ProjectID":"1","ProjectName":"Mike's Test Project"},
       {"ProjectID":"2","ProjectName":"My Second Test Project"},
       ....
    ]
}

Upvotes: 2

Related Questions