如何从 f:selectItems 获取标签和值

发布于 2024-09-07 03:17:00 字数 288 浏览 9 评论 0原文

我正在开发一个 JSF 页面,该页面具有基于 List 的下拉列表:

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

我需要获取当前所选项目的值和标签。现在我只得到价值。我也能得到这个标签吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

三五鸿雁 2024-09-14 03:17:00

你不能。这就是 HTML 的工作原理。要知道,JSF 是一个 HTML 代码生成器。 JSF 生成 HTML 元素将仅发送所选 元素的 value 属性。它不会发送其标签。

但这不应该是一个大问题。也就是说,您已经知道服务器端#{bean.availableItems}内的值和标签。要获取关联标签,您所需要做的就是通过值作为键来获取它。我建议将其设为 Map,它也可以在 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);
        // ...
    }
}

with

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

和 in result

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

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

另请参阅:

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:

神仙妹妹 2024-09-14 03:17:00

我没有像这样尝试使用 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>

Bean Company 中的 IssueDesc 基本上是 String 类型

    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;
    }


}

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).

<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

    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;
    }


}
路还长,别太狂 2024-09-14 03:17:00

如果值应该是 Integer 和 label String 并且在支持 bean 中都需要怎么办?在 bean 中使用 Map 不起作用,因为 JSF 将映射键解释为标签。理想情况下,它是一个 LinkedHashMap 并通过数字搜索文本。

通过文本(键)搜索数字(值)似乎是颠倒的。如果 JSF 的某些实现为测试添加了额外的空间或由于某种原因更改了字母大小写,该怎么办?然后从地图中找不到该值。

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.

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.

初心未许 2024-09-14 03:17:00

这样就可以解决问题了。

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;
}

在您的示例中,您将 availableItems 作为“list”传递,将 selectedItem 作为“selection”传递。该方法将返回与selectedItem对应的标签值。

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.

不必在意 2024-09-14 03:17:00

以下方法对于使用 List获取值和标签也可能很有用:

这里,facade、statesFacade 从数据库/企业 bean 获取状态列表。

在视图(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}"/>

在托管 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();
       }
    }

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.

In view (xhtml page):

    <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):

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();
       }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文