2012-09-10 34 views
0

我在play2中的表單有問題。Play2 - 表單 - > objectId

型號:

@Id private ObjectId id; 

形式

<input name="id" id="id" type="hidden" value="@guidesForm.field("id").value()"> 

我不能bindFromRequest()初始化id字段,它會永遠是空的。我只能用一個ObjectId來查詢而不是一個字符串。

ObjectId id = new ObjectId(form().bindFromRequest().get("id")); 

這是objectid的正確構造函數。正如你可以看到這是我的解決方法,我不使用guideForm.bindFromRequest();我只需要直接綁定它。

這感覺有點不好意思。是一個soltuion,我可以使用正常的綁定?

Form<Myclass> guideForm = form(Myclass.class); 
Form<Myclass> filledForm = guideForm.bindFromRequest(); 

回答

1

嘗試註冊在調用onStart)的Global object自定義的DataBinder(:

Formatters.register(ObjectId.class, new SimpleFormatter<ObjectId>() { 

    @Override 
    public ObjectId parse(String input, Locale l) throws ParseException { 

     return ...; // create the object from the input of the form 
    } 

    @Override 
    public String print(ObjectId objectId, Locale l) { 
     return String.valueOf(objectId.id); 
    } 

}); 

該文檔可在此頁的結尾:http://www.playframework.org/documentation/2.0.3/JavaForms