开发者

How to set h:selectOneMenu label as value?

I'm using h:selectOneMenu and I want to get not the ID value, but the label. In the backing bean I create SelectItem objects which are taken for loading the h:selectOneMenu.

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

My view code:

<h:selectOneMenu value="#{Metadata.thema}">
    <f:select开发者_StackOverflow中文版Items value="#{ThemaBean.themes}" /> 
    <f:valueChangeListener type="com.schober.events.SelectThemaEvent" />
</h:selectOneMenu>

The code here sets Metadata.thema with the "id", but I need to set the "label". I tried with label="#{Metadata.thema}" but it does not work for me.


Then just use the label as value. Use the SelectItem constructor taking a single argument instead:

new SelectItem("label");

This way the label will be used as both item value and item label.


Update you seem to have misphrased the question and actually want to get both. In that case, just hold a Map of ID-label value pairs yourself and get the label from the map by the selected ID.

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

// ...

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

You can reuse this Map to generate list of SelectItems or even more, if you're using JSF 2.0 and EL 2.2 you can also use that map straight inside <f:selectItems> without the need to copy it into List<SelectItem>.

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

Or if your sole intent is to redisplay the label in an output text, you can also just use

<h:outputText value="#{bean.themaIdsAndLabels[bean.thema]}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜