[Draft]
To populate ExtJs ComboBox using Spring Controller, you can create an Ajax request using Ext.data.HttpProxy and as response you can return Json Objects. And using JsonReader, you can read values and pupolate ComboBox.
Requirements
* Spring
* ExtJS 2.0
* json-lib-2.1-jdk14.jar
* spring-json-view-2.2.jar
Here is class of the combobox's item :
public class Unit {
private long id
private String name;
public Unit(long id, String name){
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
public long getId() {
return id
}
private void setId(long id) {
this.id = id;
}
}
Here is the controller. It is multiaction controller. But it does not have to be so. The request is mapped to loadUnits() method, which retrieves units from a source (here it is a method, it can be a repository), converts them to JSON object and returns a JSonView as a view.
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.JsonView;
@Controller
public class MyMultiController {
@RequestMapping("/getunits.do")
public ModelAndView loadUnits() {
//Somehow get units.
List units = getConstUnits();
return new ModelAndView(new JsonView(), "units", convertToJSON(units));
}
//Convert java objects to JSON objects
private List convertToJSON(List objects) {
List jsonObjects = new ArrayList();
for (Object object : objects) {
jsonObjects.add(JSONSerializer.toJSON(object));
}
return jsonObjects;
}
private List getUnits() {
List units = new ArrayList();
units.add(new Unit(1, "Unit 1"));
units.add(new ConstUnit(2, "Unit 2"));
return units;
}
}
Here is the ExtJs Code for ComboBox. It creates Ext.data.HttpProxy, which is an implementation of Ext.data.DataProxy that reads a data object from an Ext.data.Connection object configured to reference a certain URL. It gets data from getsunits.do url. And mode od the unit combobox is set to remote.
var unitStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url: 'getunits.do'}),
reader: new Ext.data.JsonReader({
root:'units'
}, [{name: 'id', mapping:'id'}, {name: 'name' , mapping:'name'}])
});
var unitField = new Ext.form.ComboBox({
id:'unitField',
name: 'unit',
fieldLabel: 'Unit',
store:unitStore,
mode: 'remote',
displayField: 'name',
allowBlank: false,
valueField: 'id',
hiddenName : 'unitId'
anchor:'95%',
triggerAction: 'all'
});
When you put the unitField in a form, then it will be populated when the user clicks the combobox.
I hope it is helpful.