播放表格:如何填写重复的字段?

时间:2013-06-21 15:47:44

标签: forms scala playframework-2.0 playframework-2.1

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

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()等等),我可以使用以下内容填充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
)

有更好的方法吗?

1 个答案:

答案 0 :(得分: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))
}