【问题标题】:Play framework form submit isn't passing validation播放框架表单提交未通过验证
【发布时间】:2013-02-03 04:08:53
【问题描述】:

我是 scala 和类型安全语言的新手,所以我可能会忽略一些基本的东西。这就是我的问题。

目标我想提交一个只有一个文本输入的表单,并且不反映我的案例类。它将以类型结束:String

问题无法从折叠中获得成功

我在前端有一个表单,我选择用 html 编写而不是 play 的表单助手(如果这是问题,愿意更改)

<form method="POST" action="@routes.Application.shorten()">
  <input id="urlLong" name="urlLong" type="text" placeholder="http://www.google.com/" class="span4"/>
  <div class="form-actions">
    <button type="reset" class="btn">Reset</button>
    <button type="submit" class="btn btn-primary pull-right"><span class="icon-random"></span> Shrtn It!</button>
  </div>
</form>

处理 post 动作的控制器如下所示:

import ...

object Application extends Controller {

  val newUrlForm = Form(
    "urlLong" -> text
  )

  def shorten = Action { implicit request =>
    val urlLong = newUrlForm.bindFromRequest.get

    newUrlForm.fold(
      hasErrors = { form =>
        val message = "Somethings gone terribly wrong"
        Redirect(routes.Application.dash()).flashing("error" -> message)
    },

    success = { form =>
      val message = "Woot it was successfully added!"
      Redirect(routes.Application.dash()).flashing("success" -> message)
    }
  }
  ...
}

我试图遵循/修改 Play for Scala 书中的教程,但它们的形式与案例类相匹配,而且 Play 的教程也与我的用例有所不同。连同您的答案,如果您可以包括您是如何计算出来的,那将非常有用,因此我可以更好地自行排除故障。

如果重要的话,我会使用 intellij idea 作为我的 ide

【问题讨论】:

    标签: forms scala playframework


    【解决方案1】:

    您需要在 form.bindFromRequest 上调用 fold 方法。来自documentation>处理绑定失败

    loginForm.bindFromRequest.fold(
      formWithErrors => // binding failure, you retrieve the form containing errors,
      value => // binding success, you get the actual value 
    )
    

    您也可以对单个字段使用单个 Mapping 构造

    Form(
      single(
        "email" -> email
      )
    )
    

    【讨论】:

    • 映射只是一种转换表单名称的方式,还是它们有其​​他(必要的)目的?
    • 是的,映射是一种从 html 表单映射到您自己的域对象的简单方法。在这种情况下,它是一个单独的参数,所以它没有太大帮助,实际上您应该能够直接绑定,如this answer 所示。但对于更复杂的场景,它确实非常方便
    【解决方案2】:

    我最终得到了什么:

    def shorten = Action { implicit request =>
      newUrlForm.bindFromRequest.fold(
        hasErrors = { form =>
          val message = "Somethings gone terribly wrong"
          Redirect(routes.Application.dash()).flashing("error" -> message)
        },
    
        success = { urlLong =>
          val message = "Woot it was successfully added!"
          Redirect(routes.Application.dash()).flashing("success" -> message)
        }
      )
    }
    

    不确定我是否真的理解我做错了什么,但这段基于 mericano1 答案的代码最终也能正常工作。好像以前我是从表单中取出 urlLong val 然后折叠表单,因为这会直接折叠表单,并在此过程中提取 urlLong 的 val。

    我也不确定为什么 fold 的参数记录不同。

    【讨论】:

    • 我认为您缺少的是 newUrlForm.bindFromRequest 不会对 newUrlForm 产生任何副作用,它只是返回一个新的 Form 对象,其值从请求中绑定。因此,如果您折叠 newUrlForm 而不是 newUrlForm.bindFromRequest 值不可用,因此会出现错误(您没有在表单中将 urlLong 文本标记为可选)
    猜你喜欢
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    相关资源
    最近更新 更多