PDA

View Full Version : HOWTO: pre-select a value in a combobox



bitdifferent
8 Jun 2007, 5:25 AM
Here's how to pre-select the value that a combobox will display, which took me a while to figure out (credit to anyone who helped me on this, I can't remember who though).

Short answer: use MyCombo.setValue(x) in the handler for the Load event of the DS which the Combo uses.

Long answer:



//set up data for the combo, we'll use an array for simplicity:
var MyComboData = [
[1, "Red"],
[2, "Orange"],
[3, "Yellow"],
[4, "Green"],
[5, "Blue"],
[6, "Indigo"],
[7, "Violet"]
];

//and a Data Store:
var MyComboDataStore = new Ext.data.Store
(
{
proxy: new Ext.data.MemoryProxy (MyComboData),
reader: new Ext.data.ArrayReader
(
{
id: 0 //nb: id for an ArrayReader is the column subscript, NOT the name!
},
[
'ColourID',
'ColourName'
]
)
}
);



Obviously this could be a Json-based combo if you prefer.

Now the combo itself:


var MyCombo = new Ext.form.ComboBox
(
{
//config options here eg typeAhead, triggerAction...
store: MyComboDataStore,
displayField: 'ColourName',
valueField: 'ColourID'
)
);

function WhenMyDSLoads()
{
MyCombo.setValue(4) //Green
}

//and finally
MyComboDataStore.on('load',WhenMyDSLoads);



Hope this helps someone!

Matt S.

aconran
17 Jun 2007, 6:59 PM
You could just set the value property of your config option. :-D Is it a bit easier than what you've posted above.

http://extjs.com/deploy/ext-1.1-beta1/docs/output/Ext.form.ComboBox.html#config-value

bitdifferent
25 Jun 2007, 6:54 PM
Well maybe I'm being really thick but that doesn't work for me. For a combo that has one set of 'display' values and one set of 'id' values, if I want to pre-select the id value, and have the associated display value displayed, I can't do it by just assigning a value in the constructor.

For example, in the combo I'm working on right now (and I came back to this post to read my own howto again!), what I've just tried doesn't work:



161 displayField: 'vchExpertiseLevel',
162 valueField: 'intExpertiseLevelID',
163 value: '<!--{$intPreSelectedLevelID}-->'


(BTW that's a smarty template tag, in non-standard delimiters... long story)

Anyway what I mean is that I get the number '3' in the combo instead of the text that goes with the third row in my 'expertise levels' db table. To do what I want, AFAIK you have to do it the 'long' way - but I stand ready to be corrected if there is an easier way.

Cheers

Matt S.

aconran
26 Jun 2007, 5:40 AM
Interesting.... Setting value to a relevant valueField has always pulled back and displayed the displayField for me.

Are you setting the mode to local? You could step through Combo.onLoad in firebug to see what's up. This code uses selectByValue and findRecord to retrieve the relevant displayField. I'd be interested in seeing what was wrong.