November 05, 2009

Dynamic loading of ComboBox using ExtJS

Ext JS provide us with a very flexible ComboBox widget that can be loaded locally or remotely (dynamic loading). You can also load the combo box from the server in response to an event like changing selection of another combo box. In this article I am going to walk you through an example of dynamically loading a ComboBox in a form.

For example, we have simple form to add details of country. The fields are country name, population and population type. I will keep the first two fields as normal text fields and population type as a combo box. Upon loading of the form, we need to retrieve the population type and load it into the ComboBox.

The first step would be to create a data store (Ext.data.Store) to hold our dynamically loaded data. Lets assume I have a server side method at URL /testapp/poptype.json that fetches the data from some data repository. So, here is our data store:
var ds = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url: '/testapp/poptype.json',method:'GET'}),
reader: new Ext.data.JsonReader({
root: 'rows',
fields: [ {name: 'myId'},{name: 'displayText'}] 
})
});
Please note that to load the data into the data store, I will have to call the load method. Next, we need to bind this data store to our form. The binding is done through the store attribute when we configure the drop down in the form. Here is our form:
var addCountryForm = new  Ext.form.FormPanel({
id:"addCountryForm",
title:"Add Country Form",
height:300,
closable:true,
style: {margin:5},
frame:false,
items:  [{xtype:'textfield',name:'cname',fieldLabel:'Country Name' },
{xtype:'numberfield',name:'pop',fieldLabel: 'Population'},
new Ext.form.ComboBox({                        
fieldLabel: 'Population Type',
hiddenName:'popType',
store: ds,
valueField:'myId',
displayField:'displayText',
triggerAction: 'all',
emptyText:'Select',
selectOnFocus:true,
editable: false                        
})

],
buttons: [{
text: 'Save'
},{
text: 'Cancel'
}]
});
Now, lets have a look at a sample JSON output:
{
"rows":[
{"myId": "PT1" , "displayText": "Small"},
{"myId": "PT2" , "displayText": "Medium"},
{"myId": "PT3" , "displayText": "Large"}
]
}
Hope this article helped you out. Happy coding!

Read other ExtJS related articles!

2 comments :

Ansis said...

hello,, can you help me? i have problem when submitting the form. when combo is submitted, the parameter that sent is not the id but the displayField. Here my code :

{
xtype:'combo',
fieldLabel:'Country ',
name:'cb_country',
id:'cb_country',
mode:'remote',
typeAhead: false,
loadingText: 'Searching...',
store:cb_country_store,
forceSelection:true,
emptyText:'Choose...',
triggerAction:'all',
valueField:'country_id',
displayField:'country_name',
anchor:'40%'
}

thanks before...

Unknown said...

You should change 'name' to 'hiddenName'

name:'cb_country',

change to

hiddenName:'cb_country',