1

我希望我的表单具有初始值。所以我使用.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)
4

1 回答 1

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

于 2019-05-13T07:35:30.443 回答