0

I have a ice:selectOneMenu component and need to obtain the id and value that was selected from the page:

<ice:selectOneMenu partialSubmit="true" 
 value="#{bean.selectedType}" valueChangeListener="#{bean.listenerSelectedType}">
<f:selectItems value="#{bean.typeValues}"/>
<ice:selectOneMenu/>


public List<?> getTypeValues(){ 
List<SelectItem> returnList = new ArrayList<SelectItem>();
...
//SelectItem item = new SelectItem(id, label);
SelectItem item = new SelectItem("A", "B");

returnList.add(item);
}

public void listenerSelectedType(ValueChangeEvent event) {
    ...
    //The event only has the id ("A")
    //How can I get the label ("B") that is in the page?
}
Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
user2095246
  • 45
  • 1
  • 4

1 Answers1

0

This is true, on form submit only the value of <select> HTML element will be sent to the server.

But as far as it was you who populated the selectOneMenu with both value and label attributes, the label would also be accessible if you iterate over the created collection to find what you need.

Simply put, remember the collection you created in your bean and iterate over it to get the label. This is a basic example:

@ManagedBean
@ViewScoped
public void MyBean implements Serializable {

    private List<SelectItem> col;

    public MyBean() {
        //initialize your collection somehow
        List<SelectItem> col = createCollection();//return your collection
        this.col = col;
    }

    public void listenerSelectedType(ValueChangeEvent event) {
        String value = (String)event.getNewValue();
        String label = null;
        for(SelectItem si : col) {
            if(((String)si.getValue()).equals(value)) {
                 label = si.getLabel();
            }
        }
    }

}

By the way, be sure to initialize your collection in a class constructor or in a @PostConstrct method and do not do this (business) job in a getter method - it is a bad practice.

Also, implementing your selectOneMenu with a backing Map<String, String> options might be a better choice, because the label will be accessible via a simple call: String label = options.get(value), assuming that your map contains <option value, option label> as <key, pair> of map.

Community
  • 1
  • 1
skuntsel
  • 11,624
  • 11
  • 44
  • 67
  • Thank you for your response. That´s the solution that I implemented. I thought that there was another way to obtain the label value without iterating. – user2095246 Feb 22 '13 at 11:27
  • You're welcome. The solution you speak of is based on using a `Map` instance to hold the data. – skuntsel Feb 22 '13 at 11:42
  • Also, you may choose the answer as accepted if it helped you in solving your problem. – skuntsel Feb 22 '13 at 11:43