将对象的对象绑定到表单

时间:2015-11-13 04:34:30

标签: java forms playframework-2.3 custom-formatting

我有以下模特:

public class Color {
    public String name;
    public Long id;
    public String rgb;
//setters, getters
}

public class Product {

  private static List<Product> products;

  static {
    products = new ArrayList<Product>();
    products.add(new Product("1111111111111", "Paperclips 1",
        "Paperclips description 1", new Color(1L,"yellow","ff4400")));
    products.add(new Product("2222222222222", "Paperclips 2",
        "Paperclips description ",new Color(2L,"red","ff1100")));
    products.add(new Product("3333333333333", "Paperclips 3",
        "Paperclips description 3",new Color(3L,"brown","ff8800")));
    products.add(new Product("4444444444444", "Paperclips 4",
        "Paperclips description 4",new Color(4L,"blue","ff4400")));
    products.add(new Product("5555555555555", "Paperclips 5",
        "Paperclips description 5",new Color(5L,"black","ff4400")));
  }

  @Constraints.Required
  public String ean;
  @Constraints.Required
  public String name;
  public String description;
  public Color color;

  public Product() {
  }

  public Product(String ean, String name, String description, Color color) {
    this.ean = ean;
    this.name = name;
    this.description = description;
    this.color = color;
  }
//other methods required by controller
}

显示产品形式的视图:

@(productForm: Form[Product])
@import helper._
@import helper.twitterBootstrap._

@main("Product form") {
  <h1>Product form</h1>
  @helper.form(action = routes.Products.save()) {
    <fieldset>
      <legend>Product (@productForm("name").valueOr("New"))</legend>
      @helper.inputText(productForm("ean"), '_label -> "EAN")
      @helper.inputText(productForm("name"),'_label -> "Name")
      @helper.textarea(productForm("description"), '_label -> "Description")
      @helper.inputText(@productForm("color.id"),'_label -> " @productForm('color.name') : @productForm('color.rgb')")
    </fieldset>
    <input type="submit" class="btn btn-primary">
     <a class="btn" href="@routes.Products.index()">Cancel</a>
  }
}

我的问题涉及这条线:

@helper.inputText(@productForm("color.id"),'_label -> " @productForm('color.name') : @productForm('color.rgb')")

我知道它不正确,但我需要这样的东西,即访问表单中对象的对象,它也应该像Form [Product]的任何字段一样可绑定和不可绑定。可能吗?如果没有,人们通常会如何处理此类案件?

1 个答案:

答案 0 :(得分:1)

您可以使用value访问字段的内容,例如

productForm("color.name").value.getOrElse("unknown")

如果它有点笨拙,或者您想重复使用它,可以使用defining将其定义为模板变量:

@defining( productForm("color.name").value.getOrElse("unknown")+" : "+productForm("color.rgb").value.getOrElse("-") ) { colorLabel =>
   @helper.inputText(@productForm("color.id"), '_label -> colorLabel)