表单中的多个字段,带有play application / form-url-encoded body解析器

时间:2014-05-04 12:49:29

标签: scala playframework-2.1

我有一张表格

<form action="/action" method="post">
  <input type="text" name="email[1]" />
  <input type="text" name="email[2]" />
  <input type="text" name="email[3]" />

  <button type="submit">Submit</submit>
</form>

我有playframework控制器,期待post application / form-url-encoded request

def save = Action {
  request.body.asFormUrlEncoded.map { form =>
    println( form )
    Ok("Wop wop wop")
  }.getOrElse {
    BadRequest("Bad bad bad")
  }
}

这个代码是我收到的

Map(email[1] -> List(test@test.com), email[3] -> List(), email[2] -> List(test@test.com))

而不是

Map( email -> Map( 1 -> List(test@test.com), 3 -> List(), 2 -> List(test@test.com) )

我需要提取这些数字,因为它们指向数据库中的某些内部ID。

问题:如何提取这些数字?我现在看到的唯一方法是在地图名称上进行模式匹配。也许还有更好的选择?

谢谢

1 个答案:

答案 0 :(得分:0)

我认为这里更好的解决方案是定义表单然后将其与请求绑定。 尝试类似的东西:

import play.api.mvc.Action
import play.api.data._
import play.api.data.Forms._

val form = Form(
  mapping(
    "email[1]" -> text,
    "email[2]" -> text,
    "email[3]" -> text
  )(_ :: _ :: _ :: Nil) {
    case first :: second :: third :: Nil => Option((first, second, third))
    case _ => None
  }
)

def myAction = Action{
  implicit request =>
    form.bindFromRequest().fold(errors => BadRequest, data => Ok)
}
相关问题