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

2019-08-07 21:17发布

问题:

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