How to bind complex types in play-framework 2.0

后端 未结 2 980
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 08:41

I have a model class in the following structure:

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

public class Play {
   public String name;
         


        
2条回答
  •  孤城傲影
    2020-12-25 09:24

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

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

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

提交回复
热议问题