scala:获取play.api.data.Form [String]:选项[models.User]

时间:2014-02-06 13:59:56

标签: forms scala playframework

我正在使用play.api.data.Form [String]:当试图在html视图中显示错误时选项[models.User]。

以下是我正在尝试使用的代码,如果需要,请随时重新编辑所有内容。感谢

控制器:

  val forgotPasswordForm = Form(
    single(
      "email" -> text
    ) verifying ("Invalid email or password", result => result match {
      case (e) => User.findOneByEmail(e).isDefined
    })
  )

  def forgotPassword() = withOptionUser { user => implicit request =>
    Ok(views.html.anon.forgotPassword(user))
  }

  def forgotPasswordSubmit = withOptionUser { user: User => implicit request =>
    forgotPasswordForm.bindFromRequest().fold(
      formWithErrors => {
        // do something with the bad form, like reshow the view
        BadRequest(views.html.anon.forgotPassword(formWithErrors))
      },
      submission => {
        // do something with the submitted form
        Ok("got " + forgotPasswordForm.value)
      }
    )
  }

Html:

@(  user:   Option[User]
)

@stylesheet = {
    <link rel="stylesheet" media="screen" href='@routes.Assets.at("styles/public/anon.min.css")'>
}

@main("Forgot Password",user: Option[User],"forgotPassword",stylesheet){

<section class="login">
    <div class="loginBox contentBox">
        <h1>Forgot Password?</h1>

        @if(forgotPasswordForm.hasGlobalErrors) {
            <ul>
            @forgotPasswordForm.globalErrors.foreach { error =>
                <li>error.message</li>
            }
            </ul>
        }

        <p>Enter your email address:</p>
        <form action="/forgotpassword" method="POST">
            <input type="email" name="email" placeholder="E-mail Address" id="email" data-xpl="loginEmail"/>

            <div class="greenButton">
                <input type="submit" id="loginbutton" value="submit" data-xpl="loginSubmit"/>
            </div>
        </form>
    </div>
</section>

}

1 个答案:

答案 0 :(得分:1)

formWithErrorsForm[String],您的模板期待Option[User]。我不完全理解您将Option[User]传递给忘记密码表单的原因,但该模板需要在参数列表中包含forgotPasswordForm: Form[String]

然后你可以像这样渲染模板:

Ok(views.html.anon.forgotPassword(user, forgotPasswordForm))

BadRequest(views.html.anon.forgotPassword(user, formWithErrors))