2011-08-31 3 views
1

달성하고자하는 것은 다음 링크에 게시 된 것과 매우 유사합니다.JSF에서 h : inputText + managed bean을 사용하여리스트/맵/세트를 저장하는 방법

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

나는 약간 다릅니다 그러나 내가 무엇을 달성하고자하는 위의 링크 Arjan Tijms에서 제공하는 답변을 특히 반 했어요. 다음 코드 스니 j을 고려하십시오.

빈 (bean)

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 시간 : inputText를 사용하고 저장 버튼을 클릭하면 각 h : inputText의 모든 선택 사항이 선택 목록에 추가됩니다. 나는 높고 낮게 수색했지만 어떻게 할 수 있는지에 대한 어떤 힌트도 찾을 수없는 것 같습니다.

JSF 2가 실제로 이것을 지원하지 않는다면 나는 단지 한개의 h : inputText로 못생긴 방식을 사용하고 목록을 변환하는 변환기를 사용해야하지만 여전히 이상적인 해결책을 찾을 수 있습니다.

누군가가 stackoverflow에서 나에게 올바른 방향으로 빛을 비춰 주셨으면합니다.

답변

6

"String"을 목록에 추가하는 "추가"버튼을 추가하기 만하면됩니다. 콩 뷰 범위에 넣고있을 경우에만 작동

private String newChoice; 

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

// ... 

주와

<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}" /> 

. 범위가 지정된 요청은 모든 요청에 ​​대해 작성되며 매번 목록을 다시 작성합니다.

+0

대단히 감사합니다. BalusC. 매력처럼 작동합니다. – Qcumber

+0

안녕하세요 BalusC :이 시나리오에 대한 답변을 제공해 주시겠습니까? http://stackoverflow.com/questions/19395621'varStatus'가 어떻게 작동하는지 더 자세히 설명해 주실 수 있습니까? –

관련 문제