[英]Dynamic <optgroup> support in wicket
我希望使用wicket在我的頁面中呈現<select>
標簽,但是將選項與<optgroup>
組合在一起,這在Wicket DropDownChoice中的Separator上進行了討論,但在解決方案中, <optgroup>
假設<optgroup>
標簽是靜態的,我想從數據庫中提取選項和組。
使用兩個嵌套的轉發器來迭代您的組和選項:
<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。 嵌套在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
已根據類別進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.