2013-02-18 57 views
0

我是新来的scala和类型安全的语言,所以我可以忽略一些基本的东西。这说这是我的问题。玩框架表单提交没有通过验证

目标我想提交一个只有一个文本输入的表单,并且不会镜像我的案例类。它最终将会类型:字符串

问题不能进入成功从折

我对前端的形式,我选择在HTML,而不是剧中的写形式佣工(愿意改变,如果这是问题)

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

时处理后的动作控制器看起来是这样的:

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

回答

1

你需要调用form.bindFromRequest的折叠方法。从documentation>处理绑定失败

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

你也可以使用单一的映射构建一个单场

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

是映射只是一种转换形式的名称,然后的方式,还是他们服务其他一些(必要的)目的? – AKnox 2013-02-18 20:23:00

+0

yes映射是一种将html表单映射到您自己的域对象的简单方法。在这种情况下,它是一个单一的参数,所以它没有太大的帮助,事实上,你应该能够直接绑定,如[这个答案](http://stackoverflow.com/a/9657824/152601)所示。但是,对于更复杂的场景,它确实非常方便 – mericano1 2013-02-18 22:06:19

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。

此外,我不确定为什么fold的参数记录不同。

+0

我认为你所缺少的是'newUrlForm.bindFromRequest'对'newUrlForm'没有任何副作用,它只是返回一个新的Form对象,其中绑定了来自请求的值。所以,如果你在newUrlForm而不是'newUrlForm.bindFromRequest'的值上不存在,那么错误(你没有在你的表单中标记urlLong文本是可选的) – mericano1 2013-02-18 22:13:02