2013-07-21 67 views
0

喜逢身體我工作的Primfaces頁,我必須做出一個selectOneMenu用於至極從數據庫中獲得的項目,所以我試圖使它這樣,但我仍然有問題與轉換器selectOneMenu用於轉換

所以我源代碼是如下因素:

selectOneMenu用於:

<p:selectOneMenu id="devises" required="true" value="#{pret.devise}" effect="fade" converter="devise"> 
    <f:selectItem itemLabel="Select One" itemValue="" /> 
    <f:selectItems value="#{devise.listDevise()}" var="devise" itemLabel="#{devise.nomDevise}" itemValue="#{devise}"/> 
</p:selectOneMenu> 

變換器代碼:

@FacesConverter(value = "devise") 
public class DeviseConverter implements Converter{ 

    public static List<Devise> devises = Devise.listDevise(); 

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) { 
     if (submittedValue.trim().equals("")) { 
      return null; 
     } else { 
      try { 
       int idDevise = Integer.parseInt(submittedValue); 
       for (Devise p : devises) { 
        if (p.getIdDevise()== idDevise) { 
         return p; 
        } 
       } 
      } catch(NumberFormatException exception) { 
       throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Devise")); 
      } 
     } 
     return null; 
    } 

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) { 
     if (value == null || value.equals("")) { 
      return ""; 
     } else { 
      return String.valueOf(((Devise) value).getIdDevise()); 
     } 
    } 
} 

錯誤代碼是:「圖謀:驗證錯誤:值無效」

+0

您的bean中是否有equals()和hashCode()方法? –

回答

0

你的對象Devise需要包含equals()hashCode()方法。

此外,您可以使用此generic converter這將適用於所有類型的對象,並且您將不需要爲所有選擇列表編寫轉換器。

import java.util.Map; 
import java.util.Map.Entry; 
import java.util.UUID; 
import java.util.WeakHashMap; 

import javax.faces.component.UIComponent; 
import javax.faces.context.FacesContext; 
import javax.faces.convert.Converter; 
import javax.faces.convert.FacesConverter; 

@FacesConverter(value = "entityConverter") 
public class EntityConverter implements Converter { 

    private static Map<Object, String> entities = new WeakHashMap<Object, String>(); 

    @Override 
    public String getAsString(FacesContext context, UIComponent component, Object entity) { 
     synchronized (entities) { 
      if (!entities.containsKey(entity)) { 
       String uuid = UUID.randomUUID().toString(); 
       entities.put(entity, uuid); 
       return uuid; 
      } else { 
       return entities.get(entity); 
      } 
     } 
    } 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) { 
     for (Entry<Object, String> entry : entities.entrySet()) { 
      if (entry.getValue().equals(uuid)) { 
       return entry.getKey(); 
      } 
     } 
     return null; 
    } 

} 
相關問題