如何获得f: selectitem的标签和值?

时间:2022-10-23 20:01:49

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

我正在编写一个基于列表 的下拉列表的JSF页面:

<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?

我需要同时获取当前所选项目的值和标签。现在我只得到值。我怎么能拿到这个标签呢?

5 个解决方案

#1


41  

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.

你不能。这就是HTML的工作原理。JSF是一个HTML代码生成器。JSF 生成一个HTML 元素只会发送所选的 <选项> 元素的值属性。它不会发送自己的标签。

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.

但这不应该是个大问题。您已经知道服务器端的值和标签,在#{bean.availableItems}中。要得到关联的标签,你需要做的就是把它的值作为键。我建议把它做成一张地图,反过来也可以用在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.

另一种方法是在javabean对象中封装表示实体的名称和值,并通过转换器将整个对象设置为值。

See also:

#2


3  

Instead of Using Map I tried like this and it's perfectly working for me to get both ItemValue and ItemLabel in the same property by using "ItemValue" attribute in selectItems tag.How ever provided no extra commas in the ItemLabel(@asfas....i had the same problem u mentioned so i selected this approach).

我没有使用Map,而是像这样做了,它非常适合我使用selectItems标记中的ItemValue属性,在同一属性中获得ItemValue和ItemLabel。无论ItemLabel没有提供额外的逗号(@asfas ....我也有同样的问题,所以我选择了这个方法。

<h:selectOneMenu  value="#{company.issueDesc}"   required="true" onchange="submit()">
     <f:selectItem itemLabel="-- Select a Issue -- " itemValue="0"/>  
     <f:selectItems value="#{company.issueList}" var="model" itemLabel="#{model.IssueDesc}" itemValue="#{model.Code},#{model.IssueDesc}" >
      </f:selectItems>
</h:selectOneMenu>

Basically IssueDesc is String type in Bean Company

在Bean公司中,基本上是一个字符串类型。

    public Class Company{

      private String issueDesc;    // getters and setters
      private int code;  // getters and setters
      private List<T>issueList; // getters and setters.


         public void getLblandVal(){

           String desc=getIssueDesc();
           String[] str_ary=desc.split(",");
           String s1=str_ary[0];
           String s2=str_ary[1];
          // parse **s1** to int;
    }


}

#3


2  

What if the the value should be Integer and label String and both are needed in backing bean. Using Map in bean doesn't work because JSF interprets the map key as label. Ideally it would be a LinkedHashMap and search the text by a number.

如果该值应该是整数和标签字符串,并且在支持bean中都是必需的。在bean中使用Map是无效的,因为JSF将Map key解释为label。理想情况下,它将是一个LinkedHashMap,并通过一个数字搜索文本。

Seems upside down to search number (value) by a text (key). What if some implementation of JSF adds extra space to test or letter case changes for some reason. Then the value is not found from map.

用文本(键)将搜索号(值)颠倒过来。如果JSF的某些实现增加了额外的空间来测试或字母的情况,会有什么原因呢?然后,从map中找不到该值。

#4


0  

The following approach may also be useful in getting value and label using List <SelectItem>:
Here, facade, statesFacade fetches list of states from database/enterprise bean.

下面的方法在获取值和标签使用列表 :这里,facade, statesFacade从数据库/企业bean获取状态列表时,可能也很有用。

In view (xhtml page):

鉴于(xhtml页面):

    <h:selectOneMenu id="statesSelectUi" value="#{applicationBean1.state}">
        <f:selectItems value="#{applicationBean1.stateSelectItems}"/>
        <f:ajax render="selectedItem" event="change" execute="statesSelectUi"/>
    </h:selectOneMenu>
    <br/>
    <br/>
    <h:outputText id="selectedItem" value="#{applicationBean1.selectedState}"/>

In the Managed Bean(applicationBean1.java):

在受管Bean(applicationBean1.java):

private String state;

/**
     * @return the stateSelectItems
     */
    public List<SelectItem> getStateSelectItemsItems() {
        stateSelectItems.add(new SelectItem("-1","--- Select state ---"));
        int statesCount = statesFacade.count();
        List<StateSelectItems> states;
        states = statesFacade.findAll();
        for (int i = 0; i < statesCount; i++) {
            stateSelectItems.add(new SelectItem(states.get(i).getStateSlNo(), states.get(i).getStateName()));
        }
        return stateSelectItems;
    }


       public String getSelectedState(){
       if("".equals(getState()) || getState() ==null){
        return "";
       }else{
        return "Selected State : " + getStateSelectItems.get(Integer.parseInt(getState())).getValue()+", "++ getStateSelectItems.get(Integer.parseInt(getState())).getLabel();
       }
    }

#5


-1  

This will do the trick.

这就行了。

private String getLabel(List<SelectItem> list, String selection) {
    String label = "";
    for (int i = 0; i < list.size(); i++) {
        if(selection.equals((String)list.get(i).getValue())) {
            label = (String)list.get(i).getLabel();
            break;
        }
    }

    return label;
}

In your example, you would pass in the availableItems as 'list' and selectedItem as 'selection'. This method will return the label value corresponding to the selectedItem.

在您的示例中,您可以将可用项作为“list”传递给selectedItem作为“selection”。该方法将返回对应于selectedItem的标签值。

#1


41  

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.

你不能。这就是HTML的工作原理。JSF是一个HTML代码生成器。JSF 生成一个HTML 元素只会发送所选的 <选项> 元素的值属性。它不会发送自己的标签。

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.

但这不应该是个大问题。您已经知道服务器端的值和标签,在#{bean.availableItems}中。要得到关联的标签,你需要做的就是把它的值作为键。我建议把它做成一张地图,反过来也可以用在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.

另一种方法是在javabean对象中封装表示实体的名称和值,并通过转换器将整个对象设置为值。

See also:

#2


3  

Instead of Using Map I tried like this and it's perfectly working for me to get both ItemValue and ItemLabel in the same property by using "ItemValue" attribute in selectItems tag.How ever provided no extra commas in the ItemLabel(@asfas....i had the same problem u mentioned so i selected this approach).

我没有使用Map,而是像这样做了,它非常适合我使用selectItems标记中的ItemValue属性,在同一属性中获得ItemValue和ItemLabel。无论ItemLabel没有提供额外的逗号(@asfas ....我也有同样的问题,所以我选择了这个方法。

<h:selectOneMenu  value="#{company.issueDesc}"   required="true" onchange="submit()">
     <f:selectItem itemLabel="-- Select a Issue -- " itemValue="0"/>  
     <f:selectItems value="#{company.issueList}" var="model" itemLabel="#{model.IssueDesc}" itemValue="#{model.Code},#{model.IssueDesc}" >
      </f:selectItems>
</h:selectOneMenu>

Basically IssueDesc is String type in Bean Company

在Bean公司中,基本上是一个字符串类型。

    public Class Company{

      private String issueDesc;    // getters and setters
      private int code;  // getters and setters
      private List<T>issueList; // getters and setters.


         public void getLblandVal(){

           String desc=getIssueDesc();
           String[] str_ary=desc.split(",");
           String s1=str_ary[0];
           String s2=str_ary[1];
          // parse **s1** to int;
    }


}

#3


2  

What if the the value should be Integer and label String and both are needed in backing bean. Using Map in bean doesn't work because JSF interprets the map key as label. Ideally it would be a LinkedHashMap and search the text by a number.

如果该值应该是整数和标签字符串,并且在支持bean中都是必需的。在bean中使用Map是无效的,因为JSF将Map key解释为label。理想情况下,它将是一个LinkedHashMap,并通过一个数字搜索文本。

Seems upside down to search number (value) by a text (key). What if some implementation of JSF adds extra space to test or letter case changes for some reason. Then the value is not found from map.

用文本(键)将搜索号(值)颠倒过来。如果JSF的某些实现增加了额外的空间来测试或字母的情况,会有什么原因呢?然后,从map中找不到该值。

#4


0  

The following approach may also be useful in getting value and label using List <SelectItem>:
Here, facade, statesFacade fetches list of states from database/enterprise bean.

下面的方法在获取值和标签使用列表 :这里,facade, statesFacade从数据库/企业bean获取状态列表时,可能也很有用。

In view (xhtml page):

鉴于(xhtml页面):

    <h:selectOneMenu id="statesSelectUi" value="#{applicationBean1.state}">
        <f:selectItems value="#{applicationBean1.stateSelectItems}"/>
        <f:ajax render="selectedItem" event="change" execute="statesSelectUi"/>
    </h:selectOneMenu>
    <br/>
    <br/>
    <h:outputText id="selectedItem" value="#{applicationBean1.selectedState}"/>

In the Managed Bean(applicationBean1.java):

在受管Bean(applicationBean1.java):

private String state;

/**
     * @return the stateSelectItems
     */
    public List<SelectItem> getStateSelectItemsItems() {
        stateSelectItems.add(new SelectItem("-1","--- Select state ---"));
        int statesCount = statesFacade.count();
        List<StateSelectItems> states;
        states = statesFacade.findAll();
        for (int i = 0; i < statesCount; i++) {
            stateSelectItems.add(new SelectItem(states.get(i).getStateSlNo(), states.get(i).getStateName()));
        }
        return stateSelectItems;
    }


       public String getSelectedState(){
       if("".equals(getState()) || getState() ==null){
        return "";
       }else{
        return "Selected State : " + getStateSelectItems.get(Integer.parseInt(getState())).getValue()+", "++ getStateSelectItems.get(Integer.parseInt(getState())).getLabel();
       }
    }

#5


-1  

This will do the trick.

这就行了。

private String getLabel(List<SelectItem> list, String selection) {
    String label = "";
    for (int i = 0; i < list.size(); i++) {
        if(selection.equals((String)list.get(i).getValue())) {
            label = (String)list.get(i).getLabel();
            break;
        }
    }

    return label;
}

In your example, you would pass in the availableItems as 'list' and selectedItem as 'selection'. This method will return the label value corresponding to the selectedItem.

在您的示例中,您可以将可用项作为“list”传递给selectedItem作为“selection”。该方法将返回对应于selectedItem的标签值。