如何从 f:selectItems 获取标签和值 [英] How to get both label and value from f:selectItems
问题描述
我正在处理一个 JSF 页面,该页面具有基于 List
的下拉列表:
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
生成 HTML .HTML
元素将只发送所选
元素的
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屋!