PDA

View Full Version : Adding a new element to a combo box dynamically



varmaj80
25 Nov 2014, 2:11 PM
Hello,
I am having a combo box drop down and I am getting all the values populated from the store. Now after all the values are loaded, based on a certain I need to add a new value to the combo box dynamically and this value should be the first value in the combo. I tried doing this using store.add, store.load and store.insert. But for some reason I am not seeing the new value in the dropdown.

In my view file, I am having the following field defined.

items: [
{
xtype: 'Mycombobox',
itemId: 'Name',
queryMode: 'local',
valueField: 'userId',
displayField: 'displayName',
store: Ext.create('ME.store.NameStore', {
autoDestroy: true
})
}
]
},

I have my NameStore defined as follows.

Ext.define('ME.store.AssigneeStore', {
extend: 'Ext.data.Store',
requires: ['ME.model.NameModel'],
model: 'ME.model.NameModel',
proxy: {
type: 'ajax',
url : Me.MsgHelper.getBaseUrl() + 'referenceData/getNames',
reader: {
type: 'json',
totalProperty: 'total',
root: 'data',
successProperty: 'success'
}
}
});
In the controller I am loading the combo box from the store using the following function.

loadNames: function() {
var nameStore = this.nameComboBox.getStore();

this.view.getEl().mask('Loading available names...');
nameStore .load({
scope: this,
callback: function(records, operation, success) {
console.log('Names have been loaded...');
this.view.getEl().unmask();
if(records && records.length > 0) {
var recordToSelect = records[0];
} else {
this.child('saveButton').disable();
}

}
});
I tried adding the new element in the afterRender() function using
nameStore.insert(0,{displayName: "ALL", id: "ALL"}); but it did not work.
Now, Can anyone please suggest me where exactly I should be adding the new element at. Can I do it in the loadNames() method or can I do it in afterRender(). I tried both ways but its not working. Not sure if I am missing something.

joel.watson
25 Nov 2014, 7:51 PM
Hi varmaj80--

Since your combobox is being loaded via an asynchronous request, it's likely that the afterRender() of the component finishes before the store load operation is complete; therefore, the record you're inserting is probably getting overwritten by the records added from the result of the store load(). Therefore, I would try doing it in the callback of the load() method (or by adding a listener for the load event).

Here's an example of using the load event, as well as adding a value in response to an arbitrary event (in this case, a button click):

Hope this helps!

e1h

varmaj80
26 Nov 2014, 7:00 AM
Thanks Joel,

I added the code in the callback of the onload method and it worked fine. Thanks a lot for the suggestion..

joel.watson
26 Nov 2014, 8:45 AM
Thanks Joel,

I added the code in the callback of the onload method and it worked fine. Thanks a lot for the suggestion..

Sure thing, glad it was helpful!