How to bind form field to an object in Play 2 Framework

谁说我不能喝 提交于 2019-12-24 13:58:01

问题


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.

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.

Here's the actual code

Controller

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()));
}

Model

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;
        }
    }

View

@(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

回答1:


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.

This is a link about the underlying Spring data binder link that might be helpful. I got that from the play google group



来源:https://stackoverflow.com/questions/12743404/how-to-bind-form-field-to-an-object-in-play-2-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!