如何从f:selectItems获取标签和值 [英] How to get both label and value from f:selectItems

查看:131
本文介绍了如何从f:selectItems获取标签和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个JSF页面上,该页面具有基于List<SelectItem>的下拉列表:

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?

推荐答案

您不能.这就是HTML的工作方式.您知道,JSF是HTML代码生成器. JSF <h:selectOneMenu>生成HTML <select><option>. HTML <select>元素将仅发送所选<option>元素的value属性.它不会发送标签.

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.

但这不是一个大问题.您即已经已经知道服务器端的#{bean.availableItems}内部的值和标签.您需要做的就是获取关联的标签,即按值作为键来获取它.我建议将其设置为Map,然后也可以在f:selectItems中使用它.

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.

基本启动示例:

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);
        // ...
    }
}

使用

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

和结果

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

另一种选择是将名称和值都包装在表示实体的javabean对象中,然后通过转换器将整个对象设置为值.

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.

  • Our selectOneMenu wiki page
  • How to populate options of h:selectOneMenu from database?

这篇关于如何从f:selectItems获取标签和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆