问题描述
我一直无法让我的表单绑定正常工作(基本上是Trial and Error).在Play 2.0.3(Java)中,将表单绑定到由其他对象组成的模型的正确方法是什么?
I've been having trouble getting my Form bindings to work properly(basically Trial and Error).In Play 2.0.3 (Java) What is the proper way to bind a Form to a Model which is composed of other objects ?
我整理了这个小例子来尝试并更好地理解它.但是,即使这个基本示例似乎也有问题.
I cooked up this little example to try and understand it better.But even this basic example seems to have issues.
我试图将Form绑定到的简单类具有3个字段,即纯字符串字段,字符串列表和自定义字段,该字段只是字符串的包装.提交表单时,除自定义字段保留为空之外,所有字段都将被填充.
The Simple class which I'm trying to bind the Form to has 3 fields a plain String Field,A List of Strings and a custom field which is just a wrapper around a string.On submitting the Form all the fields are populated except the custom field which remains null.
这是实际的代码
控制器
static Form<Simple> simpleform=form(Simple.class);
public static Result simpleForm(){
Form<Simple> filledForm=simpleform.bindFromRequest();
System.out.println(filledForm);
return ok(views.html.simpleForm.render(filledForm.get().toString()));
}
模型
public class Simple {
public String text;
public List<String> stringList;
public SimpleWrapper wrappedText;
@Override
public String toString(){
return text +"-"+simpleWrapper+"-"+stringList;
}
public class SimpleWrapper{
String otherText;
public SimpleWrapper(){}
public SimpleWrapper(String otherText){
this.otherText=otherText;
}
@Override
public String toString(){
return otherText;
}
}
查看
@(text:String)
@import helper._
@form(routes.Management.simpleForm()){
<input type="hidden" value="string" name="stringList[0]">
<input type="hidden" value="stringAgain" name="stringList[1]">
<input type="hidden" value="wrapped" name="wrappedText.otherText">
<input type="text" id="text" name="text">
<input type="submit" value="submit">
}
This was passed @text
推荐答案
要允许对象的自动绑定,您必须为您的类提供setter方法.在我的实验中,SimpleWrapper类缺少该setter方法,因此该类应该是
To allow for automatic binding of objects you must supply a setter method for your class.In my experiment the SimpleWrapper class was missing the setter method the class should have been
public class SimpleWrapper{
String otherText;
public SimpleWrapper(){}
public setOtherText(String otherText){
this.otherText=otherText;
}
@Override
public String toString(){
return otherText;
}
}
似乎甚至构造函数都不相关.
It appears even the constructor is irrelevant.
这是有关基础Spring数据绑定器的链接链接可能会有所帮助.我是从Google Play小组获得的
This is a link about the underlying Spring data binder link that might be helpful. I got that from the play google group
这篇关于如何将表单字段绑定到Play 2 Framework中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!