【发布时间】:2016-01-07 12:19:33
【问题描述】:
问题简述:
具有或多或少相同代码的两种形式,都采用单个值“ean”。一种形式按预期工作,另一种总是无法绑定。我包括了
println(form.data)
在每个控制器中查看发生了什么。例如,当在每个表单中输入值“h”时,工作表单会打印出来
Map(ean -> h)
打印出“损坏”表单的位置
Map()
那么为什么第二种形式不绑定值呢?
故事:
我一直在使用 Play 框架在 Scala 中做一个项目。事情进展顺利,直到我想创建一个新表单。由于某种原因,这种形式总是无法绑定。我不明白为什么会这样,所以我决定制作一个当前工作表单的“副本”,只更改变量的名称等。但是这个“复制”表单也有同样的问题!我在网上寻找了一些帮助,我能找到的最接近的问题如下:
Issue with bindFromRequest in Play! Framework 2.3
但是在尝试了发布的解决方案之后,它似乎根本没有帮助。下面我发布了相关的代码块,“ProductPartForm”是原始工作表单,“AddDealForm”是损坏的副本表单。我在某个地方犯了一个愚蠢的小错误吗?任何帮助将不胜感激。另请注意,我知道“成功”消息不起作用(正如您从评论中看到的那样),但这对我正在考虑的问题没有任何影响。
谢谢!
代码:
类:
package models
case class ProductPartForm(ean: Long) {
}
和
package models
case class AddDealForm(ean : Long) {
}
控制器:
package controllers
class Suppliers extends Controller {
private val productForm: Form[ProductPartForm] = Form(mapping("ean" -> longNumber)(ProductPartForm.apply)(ProductPartForm.unapply))
private val dealForm: Form[AddDealForm] = Form(mapping("ean" -> longNumber)(AddDealForm.apply)(AddDealForm.unapply))
def supplierList = Action {
implicit request =>
val suppliers = Supplier.findAll
Ok(views.html.supplierList(suppliers, productForm, dealForm))
}
def findByProduct = Action { implicit request =>
val newProductForm = productForm.bindFromRequest()
newProductForm.fold(
hasErrors = { form =>
println(form.data)
val message = "Incorrent EAN number! Please try again."
Redirect(routes.Suppliers.supplierList()).flashing("error" -> message)
},
success = { newProduct =>
val productSuppliers = Supplier.findByProduct(newProductForm.get.ean)
val message2 = "It worked!" //can't display message?
Ok(views.html.supplierList(productSuppliers, productForm ,dealForm)).flashing("success" -> message2)
}
)
}
def addDeal = Action { implicit request =>
val newDealForm = dealForm.bindFromRequest()
dealForm.fold(
hasErrors = { form =>
println(form.data)
val message = "Incorrent EAN number! Please try again."
Redirect(routes.Suppliers.supplierList()).flashing("error" -> message)
},
success = { newDeal =>
val message2 = "a"
Redirect(routes.Products.list).flashing("success" -> message2)
}
)
}
HTML:
@helper.form(action = routes.Suppliers.findByProduct()) {
<fieldset style="margin-left:200px">
<legend>
@helper.inputText(productForm("ean"))
</legend>
</fieldset>
<div style="padding-bottom:60px">
<input type="submit" class="btn primary" value="Submit" style="margin-left:400px">
</div>
}
@helper.form(action = routes.Suppliers.addDeal()) {
<fieldset style="margin-left:200px">
<legend>
@helper.inputText(dealForm("ean"))
</legend>
</fieldset>
<div style="padding-bottom:60px">
<input type="submit" class="btn primary" value="Submit" style="margin-left:400px">
</div>
}
路线:
POST /Suppliers controllers.Suppliers.findByProduct
POST /Suppliers/b controllers.Suppliers.addDeal
【问题讨论】:
-
该代码看起来正确,您将表单传递给 html 页面的控制器代码在哪里?
-
对不起!我忘记包含所有控制器代码 - 我现在已经编辑了。
标签: java scala playframework forms