Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

jsf - How to get both label and value from f:selectItems

I am working on a JSF page which has a dropdown based on List<SelectItem>:

<h:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>

I need to get both the value and label of the currently selected item. Right now I only get the value. How can I get the label, too?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't. That's just how HTML works. You know, JSF is a HTML code generator. The JSF <h:selectOneMenu> generates a HTML <select><option> . The HTML <select> element will only send the value attribute of the selected <option> element. It will not send its label.

But that shouldn't be a big issue. You namely already know both the value and label in the server side, inside the #{bean.availableItems}. All you need to do to get the associated label is to get it by the value as key. I suggest to make it a Map which in turn can also be used in f:selectItems.

Basic kickoff example:

public class Bean {
    private String selectedItem; // +getter +setter
    private Map<String, String> availableItems; // +getter

    public Bean() {
        availableItems = new LinkedHashMap<String, String>();
        availableItems.put("value1", "label1");
        availableItems.put("value2", "label2");
        availableItems.put("value3", "label3");
    }

    public void submit() {
        String selectedLabel = availableItems.get(selectedItem);
        // ...
    }
}

with

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

and in result

<p>Selected label is #{bean.availableItems[bean.selectedItem]}</p>

An alternative is to wrap both name and value in a javabean object representing an entity and set the whole object as value, via a converter.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...