How to get a specific attribute from an object list?
I've an array keeping a list of Group
objects. I want to set this list to the DropDownChoice
component. However I want to show the end user only the name at开发者_开发技巧tribute of Group
objects, and then get the selected values' id attribute to add database. What to do?
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes);
...
...
addUserForm.add(new Button("submit"){
@Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
DatabaseApp.java
public List<Group> getGroups() throws SQLException{
List<Group> groups = new ArrayList<Group>();
try {
String query = "SELECT * FROM [GROUP]";
Statement statement = db.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()){
int id = result.getInt("ID");
String name = result.getString("NAME");
groups.add(new Group(id, name));
}
result.close();
} catch (SQLException ex) {
throw new SQLException(ex.getMessage());
}
return groups;
}
DropDownChoice
has another constructor accepting an additional parameter of an IChoiceRenderer
that allows control of what's displayed and what's sent back with the form.
See this example.
In your code, an implementation could look approximately like
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes, new IChoiceRenderer(){
@Override
public Object getDisplayValue(Object object) {
return ((Group) object).getName();
}
@Override
public String getIdValue(Object object, int index) {
return Integer.toString(index);
}
});
...
...
addUserForm.add(new Button("submit"){
@Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
You're just creating the DropDownChoice
directly from the list of groups. It seems to me that what you really want is a model for the list of groups; see the IModel
documentation. Then you can create a custom model that returns only the name of a group instead of the whole Group
object.
精彩评论