java - play.data.Form.Field 到 play.data.Form[models.xxxx] 可能吗?

标签 java scala playframework playframework-2.0

我正在使用 PlayFramwork 和 Java 开发 Web 应用程序。 我试图在主视图中实现一个简单的表单,但在这个 View 中我添加了不同的模板。当我将参数传递给 View 时遇到一些问题。 错误是:

type mismatch; found : play.data.Form.Field required: play.data.Form[models.Document]

让我用代码来解释一下。

showUserView.scala.html 的内容/主视图

@(user: Form[User])

@import helper._
@import helper.twitterBootstrap._

@main("Test") {

<H1>SHOW USER</H1>


    @newUserView(user)

    @documentView(user("document"))

} 

问题出在这一行:

@documentView(user("文档"))

newUserView.scala.html 的内容/这工作正常

@(user: Form[User])

@import helper._
@import helper.twitterBootstrap._


<H2>User's Form</H2>

@inputText(
    user("name"), 
    '_label -> "Name: "
)

documentView.scala.html 的内容/这就是问题...

@(doc: Form[Document])

@import helper._
@import helper.twitterBootstrap._


<H2>Document's Form</H2>

    @inputText(
        doc("number"), 
        '_label -> "Number: "
    )

我正在准备 View 以接收没有字段的表单...我不想更改参数的类型。我会保留原来的模板。

对此有什么想法吗?如何将 Field 参数转换为 Form[Document]?

最佳答案

您需要在 Controller 中创建并填充两个模型,然后分别传递到主视图 ( showUserView.scala.html ):

@(userForm: Form[User], documentForm: Form[Document])
@import helper._
@import helper.twitterBootstrap._

@main("Test") {
    <H1>SHOW USER</H1>
    @newUserView(userForm)
    @documentView(documentForm)
} 

无论如何...

据我了解,您想编辑一些Document's填充上下文中的字段 User在这种情况下,您应该仅对两个 subview 使用一个表单(用户),然后在保存/更新数据的操作中通过隐藏 ID 查找相关文档:

@(userForm: Form[User])
@import helper._
@import helper.twitterBootstrap._

@main("Test") {
    <H1>SHOW USER</H1>
    @newUserView(userForm)
    @documentView(userForm)
}

documentView.scala.html

@(userForm: Form[User])
@import helper._
@import helper.twitterBootstrap._

<H2>Documents Form</H2>
<input type="hidden" name="document.id" value='@userForm("document.id").value' >
@inputText(
   userForm("document.number"), 
   '_label -> "Number: "
)

因此,在保存用户时,您可以在请求中找到文档的 ID 和新编号,并使用这些数据更新文档:

public static result saveUserAndDoc(){
    // save user as usually by binding the form...

    Integer documentId = Integer.valueOf(form().bindFromRequest().get("document.id"));

    Document document = Document.find.byId(documentId);
    document.number = Integer.valueOf(form().bindFromRequest().get("document.number"));
    document.update(documentId);
    return ok("User saved with changed document number);
}

当然该示例不包含 <form></form>标签 - 只是字段 - 您需要在适当的位置添加

关于java - play.data.Form.Field 到 play.data.Form[models.xxxx] 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13081534/

相关文章:

maven - 如何在 Play 中指定本地 jar 文件作为依赖项!框架 1.x

java - Ploeh 的 AutoFixture for .Net 是否有 Java 替代品?

java - 如何强制 Eclipse 在控制台上显示英文?

Scala - foldLeft 类型推断失败

scala - Scala 的数据类型通用编程库

scala - Play Framework 2.1.1 不解决依赖关系

java - org.hibernate.exception.ConstraintViolationException : Could not execute JDBC batch update

java - 如何将数组添加到首选项 (libGdx)

playframework - 带有 Play 框架的 cassandra

java - Play Framework 1 hibernate 集成