2

我有一个带有重复字段的表单:

case class MyForm(topics: List[Int])
val myForm: Form[MyForm] = Form(
  mapping(
    "topics" -> list(number)
  )(MyForm.apply _)(MyForm.unapply _)
)

以及相应的视图:

@form(...) {
  <h2>Topics of interest:</h2>
  @for(Topic(id, name, _) <- Topics.all) {
    @checkbox(
      bidForm(s"topics[$id]"),
      '_label -> (name + ":").capitalize,
      'value -> id.toString)
  }
  <input type="submit" id="submit" value="Save">
}

到目前为止一切顺利,如果该字段有错误,我会重新渲染它通过myForm.bindFromRequest.

我想用我的数据库中的数据预先填写表格。使用其他类型的字段(numbertextoption()),我可以使用以下内容填充 an existingMyForm

val existingMyForm = myForm.fill(MyForm(
  // Queries the database and return a list of case classes with field id: Int
  Topics.of(member).map(_.id)
))

但是,list这种方法失败了,我必须手动进行映射:

val existingMyForm = myForm.bind(
  Topics.of(member).map(t => ("topics[%s]".format(t.id), t.id.toString)).toMap
)

有一个更好的方法吗?

4

1 回答 1

1

我相信您需要将 List[Int] 显式传递给 MyForm 构造函数,即

val existingMyForm = myForm.fill(MyForm(
    Topics.of(member).map(_.id).toList
))

编辑 - 这是我适用于 Play 2.1.1 Scala 的基本实现:

case class MyForm(topics: List[Int])
case class Topic(id: Int)
val myForm: Form[MyForm] = Form(
  mapping("topics" -> list(number))(MyForm.apply _)(MyForm.unapply _)
)

val topicList:List[Topic] = List(Topic(1), Topic(2), Topic(3))

def test = Action { implicit req =>
  val existingMyForm = myForm.fill(MyForm(
    topicList.map(_.id)
  ))
  Ok(views.html.test(existingMyForm))
}
于 2013-11-21T18:02:21.937 回答