我希望我的表格具有初始值。因此,我使用了.fill
函数。但这仍然给我一个空表。我的代码有什么问题?
我的BooksController具有:
public Result edit(Integer id){
Book book = Book.findById(id);
if(book==null){
return notFound("book not found");
}
Form<Book> bookForm = formFactory.form(Book.class).fill(book);
return ok(edit.render(bookForm));
}
public Result update(Http.Request request){
Book book = formFactory.form(Book.class).bindFromRequest(request).get();
Book oldBook = Book.findById(book.id);
if(oldBook==null){return notFound("book not found");}
oldBook.title=book.title;
oldBook.author=book.author;
oldBook.price=book.price;
return redirect(routes.BooksController.front());
}
我的edit.scala.html视图具有:
@(bookForm : Form[Book])
@import helper._
<html>
<head>
<title>edit Book</title>
</head>
<body>
<h3>edit book</h3>
@helper.form(routes.BooksController.update){
@helper.inputText(bookForm("id"))
@helper.inputText(bookForm("title"))
@helper.inputText(bookForm("author"))
@helper.inputText(bookForm("price"))
<button type="submit">edit Book</button>
}
</body>
</html>
我的路线文件具有:
+nocsrf
GET /books/edit/:id controllers.BooksController.edit(id: Integer)
+nocsrf
POST /books/edit controllers.BooksController.update(request : Request)
答案 0 :(得分:1)
据此代码了解
oldBook.title=book.title;
oldBook.author=book.author;
oldBook.price=book.price;
您没有getter和setter,因此您需要激活对字段的“直接访问”。
您可以在conf/application.conf
文件中完成此操作:
play.forms.binding.directFieldAccess = true
您还可以通过调用.withDirectFieldAccess(true)
仅对一种表单启用“直接访问”:
Form<Book> bookForm = formFactory.form(Book.class).withDirectFieldAccess(true).fill(book);
更多内容:https://www.playframework.com/documentation/2.7.x/JavaForms#Defining-a-form