如何在play-framework 2.0中绑定复杂类型 [英] How to bind complex types in play-framework 2.0

查看:177
本文介绍了如何在play-framework 2.0中绑定复杂类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a model class in the following structure:

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

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

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

Now i want to have a form based on Play class. So I have an editPlay view which takes Form[Play] as an input. In the view I have a form which calls an update action on submit:

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

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

but I cannot find the right way to bind the user field in a way I'll receive it properly in the controller:

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

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

According to the API, Form.Field value is always a string. Is there some other way to automatic bind an input to the User Object?

谢谢

推荐答案

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

You can make use of custom DataBinder In the play.scla.html:

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

控制器方法中的

in your method in the controller

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

这篇关于如何在play-framework 2.0中绑定复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆