0

我正在使用h:selectOneMenu,我想获得的不是 ID 值,而是标签。在支持 beanSelectItem中,我创建了用于加载h:selectOneMenu.

new SelectItem("id", "label");

我的查看代码:

<h:selectOneMenu value="#{Metadata.thema}">
    <f:selectItems value="#{ThemaBean.themes}" /> 
    <f:valueChangeListener type="com.schober.events.SelectThemaEvent" />
</h:selectOneMenu>

这里的代码设置Metadata.thema"id",但我需要设置"label". 我试过了,label="#{Metadata.thema}"但它对我不起作用。

4

1 回答 1

2

然后只需使用标签作为值。使用SelectItem带有单个参数的构造函数:

new SelectItem("label");

这样标签将用作项目值和项目标签。


更新您似乎对问题的措辞有误,实际上想要两者兼而有之。在这种情况下,只需自己持有一Map组 ID-标签值对,然后通过所选 ID 从地图中获取标签。

private Map<Long, String> themaIdsAndLabels = new HashMap<Long, String>();

// ...

public void submit() {
    String themaLabel = themaIdsAndLabels.get(thema);
    // ...
}

您可以重用它Map来生成SelectItems 列表甚至更多,如果您使用 JSF 2.0 和 EL 2.2,您也可以直接在内部使用该映射,<f:selectItems>而无需将其复制到List<SelectItem>.

<f:selectItems value="#{bean.themaIdsAndLabels.entrySet()}" var="entry" itemValue="#{entry.key}" itemLabel="#{entry.value}" />

或者,如果您的唯一目的是在输出文本中重新显示标签,您也可以使用

<h:outputText value="#{bean.themaIdsAndLabels[bean.thema]}" />
于 2011-09-01T12:54:50.367 回答