Question

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:selectItems 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.

Was it helpful?

Solution

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]}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top