2011-08-31 50 views
1

我試圖實現的目標與以下鏈接中發佈的內容非常相似。如何使用h:inputText +託管bean在JSF中保存列表/地圖/集合

How to save an array in JSF with ui:repeat + h:inputText + managed bean?

我與阿爾揚Tijms在上面的鏈接,但是我想達到的目標略有不同提供的答案特別着迷。考慮下面的代碼片段。

豆子

import javax.annotation.PostConstruct; 
import javax.inject.Named; 
import javax.enterprise.context.RequestScoped; 

@RequestScoped 
@Named 
public class MyBean { 

    List<String> choices; 

    public List<String> getChoices() { 
     return choices; 
    } 

    @PostConstruct 
    public void initChoices() { 
     choices= new ArrayList<String>(); 
    } 

    public String save() { 
     // should save all the choices into some repository 
     return ""; 
    } 
} 

和的facelet頁

<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html"   
    xmlns:ui="http://java.sun.com/jsf/facelets"> 

    <h:body> 

     <h:form> 
      <ui:repeat value="#{myBean.choices}" varStatus="status">    
       <h:inputText value="#{myBean.choices[status.index]}" /> 
      </ui:repeat> 
      <h:commandButton value="Save" action="#{myBean.save}" /> 
     </h:form> 
    </h:body> 
</html> 

的事情是,如果我們在列表中開始有一些初步的數據,這將工作。初始列表爲空的情況如何?

我正在尋找的理想解決方案是每個選項都有1個h:inputText,並且當單擊保存按鈕時,每個h:inputText中的所有選項都會添加到選項列表中。我搜索了高和低,但似乎無法找到任何提示如何做到這一點。

如果JSF 2真的不支持這個,我想我只能用一個h:inputText來使用醜陋的方法,並使用轉換器來轉換列表,但我仍然希望理想的解決方案可以找到。

希望有人從stackoverflow可以爲我正確的方向發光。

回答

6

只需添加一個「添加」按鈕,將新的String添加到列表中。

<ui:repeat value="#{myBean.choices}" varStatus="status">    
    <h:inputText value="#{myBean.choices[status.index]}" /> 
</ui:repeat> 
<h:inputText value="#{myBean.newChoice}" /> 
<h:commandButton value="Add" action="#{myBean.add}" /> 
<h:commandButton value="Save" action="#{myBean.save}" /> 

private String newChoice; 

public void add() { 
    choices.add(newChoice); 
    newChoice = null; 
} 

// ... 

注意,如果豆放在視圖範圍內這僅適用。每個請求都會構造一個範圍爲1的請求,並在此重新創建列表。

+0

非常感謝BalusC。奇蹟般有效。 – Qcumber

+0

Hi BalusC:你會回答這個場景的工作嗎? http://stackoverflow.com/questions/19395621你能解釋更多關於'varStatus'如何工作。 –