2013-02-21 117 views
0

我有一个ice:selectOneMenu组件并需要获得从页面中选择的ID和值:获取标签的ID和值在冰

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

回答

0

这是真实的,在提交表单只值<select> HTML元素将被发送到服务器。

但是,只要您是使用值和标签属性填充了selectOneMenu,如果您遍历所创建的集合以找到所需内容,也可以访问此标签。

简而言之,请记住您在bean中创建的集合并遍历它以获取标签。这是一个基本的例子:

@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(); 
      } 
     } 
    } 

} 

顺便说一句,一定要初始化您的收藏在类的构造函数或在@PostConstrct方法和getter方法不这样做(业务)的工作 - 这是a bad practice

同时,实现您selectOneMenu与背衬Map<String, String> options可能是一个更好的选择,因为标签将通过一个简单的调用是可访问:String label = options.get(value),假设你的地图包含<option value, option label>作为地图的<key, pair>

+0

感谢您的回复。这是我实施的解决方案。我认为还有另一种方法可以在不迭代的情况下获得标签值。 – user2095246 2013-02-22 11:27:36

+0

不客气。您所说的解决方案基于使用“Map”实例来保存数据。 – skuntsel 2013-02-22 11:42:56

+0

此外,您可以选择答案作为接受,如果它帮助你解决你的问题。 – skuntsel 2013-02-22 11:43:40