如何在play-framework 2.0中绑定复杂类型

我有一个以下结构的模型类:

public class User { public String name; public Long id; } public class Play { public String name; public User user; } 

现在我想要一个基于Play类的表单。 所以我有一个editPlay视图,它将Form[Play]作为输入。 在视图中,我有一个表单,它在提交时调用更新操作:

 @form (routes.PlayController.update()) {..} 

但我找不到以我在控制器中正确接收它的方式绑定用户字段的正确方法:

 Form formPlay = form(Play.class).bindFromRequest(); Play playObj = formPlay.get(); 

根据API , Form.Field值始终是一个字符串。 是否有其他方法可以自动将输入绑定到用户对象?

谢谢

您可以在play.scla.html中使用自定义DataBinder

 @form (routes.PlayController.update()) {  } 

在控制器中的方法中

 public static Result update() { // add a formatter which takes you field and convert it to the proper object // this will be called automatically when you call bindFromRequest() Formatters.register(User.class, new Formatters.SimpleFormatter(){ @Override public User parse(String input, Locale arg1) throws ParseException { // here I extract It from the DB User user = User.find.byId(new Long(input)); return user; } @Override public String print(User user, Locale arg1) { return user.id.toString(); } }); Form formPlay = form(Play.class).bindFromRequest(); Play playObj = formPlay.get(); } 

我不太确定我理解你的问题,但基本上我一直在处理这样的表格:

  final static Form playForm = form(Play.class); ... public static Result editPlay(){ Form newPlayForm = form(User.class).bindFromRequest(); Play newPlay = newPlayForm.get(); .... } 

我使用以下命令从动作中提供并呈现模板:

 return ok(play_form_template.render(playForm)); 

然后在模板中:

  @(playForm: Form[Play]) @import helper._ @helper.form(action = routes.Application.editPlay()) { @helper.inputText(playForm("name")) ... }