I want to render a ComboBox that has an initial value. The ComboBox is backed by a JsonStore that loads data from some HTTP endpoint. I expect the display field to be displayed, but instead I see the value.
As a workaround, I can wait to set the initial value until the store is loaded. But that seems like a hacky workaround for such a simple use case.
Is there an easier way to render the initial display field for my ComboBox?
Here is an example. You can drop this code in any ExtJS 3.4 Fiddle.
var remoteStore = new Ext.data.JsonStore({
url: 'https://jsonplaceholder.typicode.com/todos',
autoLoad: true,
fields: ['id', 'title']
});
var remoteCombo = new Ext.form.ComboBox({
fieldLabel: 'Remote Store (busted)',
triggerAction: 'all',
mode: 'local',
store: remoteStore,
valueField: 'id',
displayField: 'title',
value: '2',
});
// Workaround: only set the value AFTER the store is loaded.
// remoteStore.on('load', () => remoteCombo.setValue('2'));
new Ext.FormPanel({
renderTo: Ext.getBody(),
items: remoteCombo
});
Why not to override the missing feature (Yes, looks like it is missing):
Ext.define('Override.form.ComboBox', {
override : 'Ext.form.ComboBox',
defaultValue: null,
initComponent : function() {
this.setDefaultValue();
Ext.form.Checkbox.superclass.initComponent.call(this);
},
setDefaultValue: function() {
if(this.defaultValue !== null) {
if(this.getStore().lastOptions === null) {
this.getStore().on('load', function(store) {
this.setValue(this.defaultValue);
}, this, {single: true});
} else {
// How to avoid else here? :-/
this.setValue(this.defaultValue);
}
}
}
});
//-------------------------
var remoteStore = new Ext.data.JsonStore({
url: 'https://jsonplaceholder.typicode.com/todos',
autoLoad: true,
fields: ['id', 'title']
});
var remoteCombo = new Ext.form.ComboBox({
fieldLabel: 'Remote Store (busted)',
triggerAction: 'all',
mode: 'local',
store: remoteStore,
valueField: 'id',
displayField: 'title',
defaultValue: '2', // <-- New Property
});
// Workaround: only set the value AFTER the store is loaded.
// remoteStore.on('load', () => remoteCombo.setValue('2'));
new Ext.FormPanel({
renderTo: Ext.getBody(),
items: remoteCombo
});
I have not used ExtJs v3.4 for about 10 years or more..