播放框架表单提交未通过验证

时间:2013-02-18 16:47:14

标签: forms scala playframework

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

目标我想提交一个只是一个文本输入的表单,并且不会镜像我的case类。它将以类型: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作为我的想法

2 个答案:

答案 0 :(得分:1)

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

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
  )
)

答案 1 :(得分:0)

我最终得到了什么:

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。

此外,我不确定为什么折叠的论据有不同的记录。

相关问题