How do you go about creating ExtJS components on the fly?
I have been working on a reports viewer web application that uses ExtJS. Its main goal is to allow users to type in or select values for the parameters of any report available, run the report and view the results.
For this application, the available reports are not known beforehand, and one of the challenges I am facing is the fact that the user interface elements that will allow users to enter values for the report parameters need to be created and added to their containers on the fly, upon reading a report definition file for the report selected by the user.
Here is a simplified version of the approach I am taking. Even though I am not an ExtJS expert, I am presenting it hoping that it will help some of you.
First, I created a few helper functions that build the different UI elements I am going to need, combo boxes, radio groups, checkbox groups, etc.
function CreateComboBox() {
var combo = new Ext.form.ComboBox({
store: CreateSimpleStore(),
displayField: 'name',
typeAhead: true,
mode: 'local',
forceSelection: true,
triggerAction: 'all',
emptyText: 'Select item...',
selectOnFocus: true,
fieldLabel: 'ComboBox'
});
return combo;
}
function CreateCheckBoxGroup() {
var grp = new Ext.form.CheckboxGroup({
fieldLabel: 'CheckboxGroup',
columns: 1,
items: [{boxLabel: 'Box 1', checked: true}, {boxLabel: 'Box 2', checked: false}]
});
return grp;
}
function CreateRadioButtonGroup() {
var grp = new Ext.form.RadioGroup({
fieldLabel: 'RadioGroup',
columns: 1,
items: [{ boxLabel: 'Radio 1', checked: true }, { boxLabel: 'Radio 2', checked: false}]
});
return grp;
}
And then I wrote a function that, called once a report definition has been retrieved from the server, will dynamically compose the required user interface elements and add them to their container.
function AddControlsHandler(button, evt) {
switch (button.text) {
case 'Add ComboBox':
mainPanel.add(CreateComboBox());
mainPanel.doLayout();
break;
case 'Add CheckboxGroup':
mainPanel.add(CreateCheckBoxGroup());
mainPanel.doLayout();
break;
case 'Add RadioGroup':
mainPanel.add(CreateRadioButtonGroup());
mainPanel.doLayout();
break;
}
}
I hope this is useful. Please let me know about the approaches you use. I am sure that, like with any other software topic, there are many ways to tackle the challenge presented here.
Downloads
Download the full sample from my downloads page.