2013-04-17 67 views
3

我使用selectOneMenu用於這樣的:selectOneMenu用於驗證錯誤:值無效

<h:selectOneMenu value="#{MyBean.zajecie.przedmiot}"> 
    <f:selectItems value="#{MyBean.przedmioty}" var="p" 
     itemLabel="#{p.nazwa}" itemValue="#{p}" /> 
    <f:converter converterId="converter.PrzedmiotConverter" /> 
</h:selectOneMenu> 

爲myBean:

private Zajecie zajecie;//+set get 
private List<Przedmiot> przedmioty;//+set get 

@PostConstruct 
private void init() { 
    przedmioty = przedmiotDao.findByLogin("login"); 
    zajecie = new Zajecie(); 
} 

和轉換器的方法:

public Object getAsObject(FacesContext context, UIComponent component, String value) { 
    PrzedmiotDao przedmiotDao = DaoFactory.getInstance().getPrzedmiotDao(); 
    Przedmiot przedmiot = przedmiotDao.findById(Przedmiot.class, Integer.parseInt(value)); 
    return przedmiot; 
} 

public String getAsString(FacesContext context, UIComponent component, Object value) { 
    Przedmiot przedmiot = (Przedmiot) value; 
    String idAsString = String.valueOf(przedmiot.getPrzedmiotId()); 
    return idAsString; 
} 

的selectOneMenu用於組件正在填充,因爲它應該。當我提交時,它顯示Validation Error: Value is not valid。我知道我需要一個適當的equals()方法爲我的實體,所以我用eclipse只使用id字段生成它。然後我不得不將測試getClass() != obj.getClass()更改爲obj instanceof Przedmiot,因爲obj.getClass()返回如下所示:Przedmiot_$$_javassist_1。我不確定這是否相關,因爲畢竟obj證明是null。我究竟做錯了什麼?

編輯:

爲myBean是ViewScoped。

有趣的是,使用相同轉換器的類似代碼在應用程序的其他部分工作。不同的是,在工作部分,我只是查看類型Przedmiot的列表,我以另一種方式獲得它。

@PostConstruct 
private void init() { 
    student = studentDao.findByLogin(ra.getUser()); 
} 

<h:selectOneMenu value="#{otherBean.przedmiot}"> 
    <f:selectItems value="#{otherBean.student.grupa.przedmiots}" var="p" 
     itemLabel="#{p.nazwa}" itemValue="#{p}" /> 
    <f:converter converterId="converter.PrzedmiotConverter" /> 
</h:selectOneMenu> 

回答

1

在您的轉換器:Integer.parseInt(value),並在<f:selectItems設置itemValue="#{p}",所以每個#{p}Przedmiot類型的實例。

參見: Why selectOneMenu Send ItemLabel to the converter?

+0

那不行。我無法將字符串轉換爲Przedmiot。在您提供的鏈接中解釋過的價值不代表一個唯一的ID嗎? – user2270884

+0

哦,很抱歉,您在載入頁面或提交給服務器時出錯? –

+0

提交。驗證失敗。 – user2270884

4

解決它。這當然寫得很差equals()方法。 首先,我的問題出現了一個錯誤。 obj未解析爲空,但other.przedmiotId沒有解析爲空。對不起。看看eclipse生成的方法:

@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (!(obj instanceof Przedmiot))//changed this from (getClass() != obj.getClass()) 
     return false; 
    Przedmiot other = (Przedmiot) obj; 
    if (przedmiotId == null) { 
     if (other.przedmiotId != null) 
      return false; 
    } else if (!przedmiotId.equals(other.przedmiotId)) 
     return false; 
    return true; 
} 

問題出在other.przedmiotId。當使用getter other.getPrzedmiotId()獲取該值時,它不會再解析爲空。

相關問題