October 03, 2009

selecting from a combobox, populated using JsonStore in extjs

gotcha.. it took me quite sometime in figuring this out. I was populating the combobox from a JsonStore and then wanted to select one of the values by default.

The documentation for
setValue(String v) : Ext.form.Field 
says:
Sets the specified value into the field. If the value finds a match, 
the corresponding record text will be displayed in the field. If the 
value does not match the data value of an existing item, and the 
valueNotFoundText config option is defined, it will be displayed as 
the default field text. Otherwise the field will be blank (although 
the value will still be set).
Parameters:

    * value : String
      The value to match

However it doesn't say what does it mean by "value into the field". Atleast i got confused and was trying with all sorts of permutation/combination (this is what happens when you get stuck with something and don't know a way out). It did mean the value that you want to submit along with the form. So just in case some poor soul is stuck like me, here is the code on how to do it.
var jsonStore = new Ext.data.JsonStore({
        storeId: 'my-json-store',
        // store configs
        autoDestroy: true,
        autoLoad: true,
        proxy: new Ext.data.HttpProxy({
            url: /relative_backend_url, 
            method: 'GET'
        }),
        // reader configs
        root: 'response',
        idProperty: 'elemId',
        fields: [ 'name', 'elemId', 'description' ]
    });

jsonStore.on('load', function(store, data){
    Ext.each(data, function (elem){
            if(elem['name'] == some_value_to_compare) {
                var combo = Ext.getCmp('my-json-combo');
                combo.setValue(elem['elemId']);
            }
 });
     // or if you already know the value of elemId, lets call it xValue for which you 
     // want to show the element, go for combo.setValue(xValue)
});

JSON response from the backend looks something like this:
{
    "response": [{
        "description": "Some long description",
        "name": "Name of the element",
        "elemId": "af02a9d6-a11c-11de-bcd5-b2e876978f0a"
    }],
    "success": true
}

No comments: