Scala Play:如何使用重复和嵌套的值呈现表单映射?

时间:2019-05-22 23:26:28

标签: scala playframework play-framework-2.7

我正在使用Scala Play 2.7.x(您可以在play-silhouette-seed googleauth branch处签出项目),并且我将表单定义为:

object TotpSetupForm {
  val form = Form(
    mapping(
      "sharedKey" -> nonEmptyText,
      "scratchCodes" -> seq(mapping(
        "hasher" -> nonEmptyText,
        "password" -> nonEmptyText,
        "salt" -> optional(nonEmptyText)
      )(PasswordInfo.apply)(PasswordInfo.unapply)),
      "scratchCodesPlain" -> optional(seq(nonEmptyText)),
      "verificationCode" -> nonEmptyText(minLength = 6, maxLength = 6)
    )(Data.apply)(Data.unapply)
  )

  case class Data(
    sharedKey: String,
    scratchCodes: Seq[PasswordInfo],
    scratchCodesPlain: Option[Seq[String]],
    verificationCode: String = "")
}

PasswordInfo来自Play-Silhouette的地方,看起来像:

case class PasswordInfo(
  hasher: String,
  password: String,
  salt: Option[String] = None
) extends AuthInfo    

在我的控制器中,填充表单,并将其作为参数传递给我的视图模板,如下所示。请注意,我已经调试了它,并且totpInfo.scratchCodes有5个值,并且表格已正确填充:

val formData = TotpSetupForm.form.fill(TotpSetupForm.Data(totpInfo.sharedKey, totpInfo.scratchCodes, totpInfo.scratchCodesPlain))
Ok(views.html.someView(formData, ...)

我按如下所示渲染视图,请注意,我确实读过the Scala Forms Repeated Values documentation note :)

@helper.form(action = controllers.routes.TotpController.submit()) {
    @helper.CSRF.formField
    @b3.text(totpForm("verificationCode"), '_hiddenLabel -> messages("verificationCode"), 'placeholder -> messages("verificationCode"), 'autocomplete -> "off", 'class -> "form-control input-lg")
    @b3.hidden(totpForm("sharedKey"))
    @helper.repeatWithIndex(totpForm("scratchCodes"), min = 1) { (scratchCodeField, index) =>
        @b3.hidden(scratchCodeField, '_label -> ("scratchCode #" + index))
    }
    <div class="form-group">
        <div>
            <button id="submit" type="submit" value="submit" class="btn btn-lg btn-primary btn-block">@messages("verify")</button>
        </div>
    </div>
}

即使正确地填充了表格的scratchCodes序列,每个序列值仍呈现为空:

<input type="hidden" name="scratchCodes[0]" value="" >
<input type="hidden" name="scratchCodes[1]" value="" >
<input type="hidden" name="scratchCodes[2]" value="" >
<input type="hidden" name="scratchCodes[3]" value="" >
<input type="hidden" name="scratchCodes[4]" value="" >

序列中的字段数正确。

我也尝试使用@helper.repeat替代方法,甚至使用@helper.input代替@b3.hidden,只是为了确保结果始终相同...我得到空值{ {1}}个元组已呈现。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

确定是罪魁祸首:重复+嵌套值需要像这样分别访问每个属性:

@helper.repeat(totpForm("scratchCodes"), min = 1) { scratchCodeField =>
  @b3.hidden(scratchCodeField("hasher"))
  @b3.hidden(scratchCodeField("password"))
  @b3.hidden(scratchCodeField("salt"))
}

然后可以正常工作,并且发布请求可以正确填充PasswordInfo UDT的序列。