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

Sha*_*rko 8 java playframework-2.0

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

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

public class Play {
   public String name;
   public User user;
}
Run Code Online (Sandbox Code Playgroud)

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

@form (routes.PlayController.update()) 
{..}
Run Code Online (Sandbox Code Playgroud)

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

Form<Play> formPlay = form(Play.class).bindFromRequest();
Play playObj = formPlay.get();
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Ahm*_*ani 15

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

@form (routes.PlayController.update()) 
{
  <input type="hidden" name="user" id="user" value="@play.user.id"/>
}
Run Code Online (Sandbox Code Playgroud)

在控制器中的方法中

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<User>(){
    @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<Play> formPlay = form(Play.class).bindFromRequest();
  Play playObj = formPlay.get();
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以将寄存器调用放在全局对象或类似的地方,以便在每个控制器中都不需要这个样板代码? (2认同)

wfb*_*ale 2

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

 final static Form<Play> playForm = form(Play.class);
 ...
 public static Result editPlay(){
     Form<Play> newPlayForm = form(User.class).bindFromRequest();
     Play newPlay = newPlayForm.get();
     ....    
 }
Run Code Online (Sandbox Code Playgroud)

我使用以下操作从操作中提供和渲染模板:

return ok(play_form_template.render(playForm));
Run Code Online (Sandbox Code Playgroud)

然后在模板中:

 @(playForm: Form[Play])
 @import helper._

 @helper.form(action = routes.Application.editPlay()) {
      @helper.inputText(playForm("name"))
      ...
 }
Run Code Online (Sandbox Code Playgroud)