玩!表单总是有错误

时间:2016-07-25 00:38:30

标签: java scala playframework-2.0

我是新手!我遇到了一些总是有错误的表格。即使所有字段都已填满,我也无法弄清楚问题是什么。

路由

GET     /products/                  controllers.Products.list()
GET     /products/new               controllers.Products.newProduct()
POST    /products/                  controllers.Products.save()

产品的Controller.java

import play.data.Form;

private final static Form<Product> productForm = form(Product.class);

public static Result list() {
    List<Product> productList = Product.findAll();
    return ok(list.render(productList));
}

public static Result newProduct() {
    return ok(details.render(productForm));
}

public static Result save() {
    Form<Product> boundForm = productForm.bindFromRequest();
    if(boundForm.hasErrors()) {
        flash("error",
                "Please correct the form below.");
        return badRequest(details.render(boundForm));
    }

    // For mystery reasons, in this line, product is always null
    // Product product = boundForm.get();

    Product product = new Product();
    product.ean = boundForm.data().get("ean");
    product.name = boundForm.data().get("name");
    product.description = boundForm.data().get("description");
    product.save();

    flash("success",
            String.format("Successfully added product %s", product));

    return redirect(routes.Products.list());
}

产品的Model.java

import static play.data.validation.Constraints.Required;

public class Product {

    @Required
    public String ean;
    @Required
    public String name;
    public String description;
    ... 
}

产品的form.scala.html

@(productForm: Form[Product])


@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")

        </fieldset>
        <input type="submit" class="btn btn-primary" value="Save">
        <a class="btn" href="@routes.Products.list()">Cancel</a>
    }
}

这是调试器的截图,也有数据和错误:(

Using debugger

我做错了什么?

~~~~更新~~~~~

我添加了列表路由和控制器操作

这是回购:

https://github.com/LTroya/up-and-running-play

1 个答案:

答案 0 :(得分:1)

解决方案 - 在java实现中需要bean(缺少setter):

public class Product {

    @Required
    public String ean;
    @Required
    public String name;
    public String description;
        public String getEan() {
        return ean;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setEan(String ean) {
        this.ean = ean;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setName(String name) {
        this.name = name;
    } 
}