我希望<select>
使用 wicket 在我的页面中呈现标签,但将选项与 分组,这在 Wicket DropDownChoice 中的 Separator 上进行了<optgroup>
讨论,但在解决方案中假设标签是静态的,我想拉两个数据库中的选项和组。<optgroup>
<optgroup>
3 回答
使用两个嵌套转发器来迭代您的组和选项:
<select wicket:id="select">
<optgroup wicket:id="group">
<option wicket:id="option"></option>
</optgroup>
</select>
我遇到了基本相同的问题。在寻找一个简短的解决方案几天后,我相信最有效的方法是使用中继器、容器和 AttributeModifier,以获得最大的灵活性,例如:
<select wicket:id="select">
<wicket:container wicket:id="repeatingView">
<optgroup wicket:id="optGroup">
<wicket:container wicket:id="selectOptions">
<option wicket:id="option"></option>
</wicket:container>
</optgroup>
</wicket:container>
</select>
在 Java 代码中,“select”是一个 Select;“repeatingView”是一个重复视图。嵌套在 RepeatingView 中有一个由 .newChildId() 命名的 WebMarkupContainer。嵌套在里面的是另一个代表“optGroup”的 WebMarkupContainer。在第二个 WMC 内部是一个 AttributeModifier,它向 optgroup 添加动态标签,以及一个处理“selectOptions”和“option”的 SelectOptions。就像是:
Select select = new Select("select");
add(select);
RepeatingView rv = new RepeatingView("repeatingView");
select.add(rv);
for(String groupName : groupNames){
WebMarkupContainer overOptGroup = new WebMarkupContainer(rv.newChildId());
rv.add(overGroup);
WebMarkupContainer optGroup = new WebMarkupContainer("optGroup");
overOptGroup.add(optGroup);
optGroup.add(
new AttributeModifier("label",true,new Model<String>(groupName))
);
optGroup.add(
new SelectOptions<MyBean>(
"selectOptions",listOfBeanOptionsForThisGroup,new MyBeanRenderer()
)
);
}
(这是假设字符串直接作为组名传递,并且选项引用 MyBean 类型的 bean,列在变量 listOfBeanOptionsForThisGroup 中)
我想将这个解决方案重构为使用更少嵌套的东西应该不难,如果有人有建议,我会将它们编辑成答案并归功于他们。使用 ListView 而不是 RepeatingView 也应该减少代码大小。
好的,所以目前我的解决方案是有这样的东西:
interface Thing {
String getCategory();
}
接着:
List<Thing> thingList = service.getThings();
DropDownChoice<Thing> dropDownChoice = new DropDownChoice<Thing>("select",
thingList) {
private static final long serialVersionUID = 1L;
private Thing last;
private boolean isLast(int index) {
return index - 1 == getChoices().size();
}
private boolean isFirst(int index) {
return index == 0;
}
private boolean isNewGroup(Thing current) {
return last == null
|| !current.getCategory().equals(last.getCategory());
}
private String getGroupLabel(Thing current) {
return current.getCategory();
}
@Override
protected void appendOptionHtml(AppendingStringBuffer buffer,
Thing choice, int index, String selected) {
if (isNewGroup(choice)) {
if (!isFirst(index)) {
buffer.append("</optgroup>");
}
buffer.append("<optgroup label='");
buffer.append(Strings.escapeMarkup(getGroupLabel(choice)));
buffer.append("'>");
}
super.appendOptionHtml(buffer, choice, index, selected);
if (isLast(index)) {
buffer.append("</optgroup>");
}
last = choice;
}
};
这要求thingList
已经根据类别进行了排序。