How to get both label and value from f:selectItems

前端 未结 5 1235
长发绾君心
长发绾君心 2020-11-30 06:05

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


    <         


        
5条回答
  •  天命终不由人
    2020-11-30 06:35

    You can't. That's just how HTML works. You know, JSF is a HTML code generator. The JSF generates a HTML element will only send the value attribute of the selected 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 availableItems; // +getter
    
        public Bean() {
            availableItems = new LinkedHashMap();
            availableItems.put("value1", "label1");
            availableItems.put("value2", "label2");
            availableItems.put("value3", "label3");
        }
    
        public void submit() {
            String selectedLabel = availableItems.get(selectedItem);
            // ...
        }
    }
    

    with

    
        
    
    

    and in result

    Selected label is #{bean.availableItems[bean.selectedItem]}

    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:

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

提交回复
热议问题