我正在尝试为简单的产品页面制作CRUD表单。我有一个奇怪的问题,每当我尝试插入新产品时,我总是将旧产品更新,因此每次我保存时总会有一个产品更新。
我的index.scala.html
如下
@main("Product List"){
@inputText(productForm("search"),'_label -> "Search",'id -> "search")
<h3>@products.size() product(s)</h3>
<table class="table table-condensed">
<thead>
<tr>
<th>Title</th>
<th>Cost</th>
<th>Price</th>
<th>Promo Price</th>
<th>Savings</th>
<th>On Sale</th>
</tr>
</thead>
<tbody>
@for(product <- products){
<tr>
<td>
@product.title
</td>
<td>
@product.pricing.cost
</td>
<td>
@product.pricing.price
</td>
<td>
@product.pricing.promoPrice
</td>
<td>
@product.pricing.savings
</td>
<td>
@product.pricing.onSale
</td>
<td>
@helper.form(action = routes.Application.deleteProduct(product.id)){
<input type="submit" value="Delete"/>
}
</td>
</tr>
}
</tbody>
</table>
<h2>Add new product</h2>
@form(action = routes.Application.newProduct()){
@inputText(productForm("title"),'_label -> "Title")
@inputText(productForm("pricing.cost"),'_label -> "Cost")
@inputText(productForm("pricing.price"),'_label -> "Price")
@inputText(productForm("pricing.promoPrice"),'_label -> "Promo Price")
@inputText(productForm("pricing.savings"),'_label -> "Savings")
@checkbox(productForm("pricing.onSale"),'_label -> "On Sale")
<input type="submit" class="btn btn-default" value="Add"/>
}
}
我的Application.java
如下,
public class Application extends Controller {
....
static Form<Product> productForm = new Form<Product>(Product.class);
public static Result products() {
return ok(views.html.index.render(Product.all(), productForm));
}
public static Result newProduct() {
Form<Product> filledForm = productForm.bindFromRequest();
if (productForm.hasErrors()) {
return badRequest(views.html.index
.render(Product.all(), filledForm));
} else {
Product.create(filledForm.get());
return redirect(routes.Application.products());
}
}
}
我的模型Product.java
如下,
public class Product {
private static final long serialVersionUID = 94587092799205246L;
@Id
public long id;
@Required
public String title;
@Required
public Pricing pricing;
public Product(){
}
public Product(String title){
this.title = title;
}
private static JacksonDBCollection<Product, Long> products = MongoDB
.getCollection("product", Product.class, Long.class);
public static List<Product> all() {
return Product.products.find().toArray();
}
public static void create(Product product) {
Product.products.save(product);
}
public static void delete(Long id) {
Product p = Product.products.findOneById(id);
if(p != null){
Product.products.remove(p);
}
}
}
我不确定是否因为表单被声明为静态或表单未在某处清除。额外的一双眼睛在这里会有很大的帮助。谢谢你的时间
答案 0 :(得分:0)
尝试
@Id
@ObjectId
public String id;
添加@ObjectId
并输入String
。似乎id无法按@marcinn
来自docs
如果服务器收到的文档没有_id字段 首先,然后服务器将字段移动到开头。