Rya*_*yan 10 scala playframework-2.0
也许我只是忽略了一些显而易见的东西,但我无法弄清楚如何将一个表单字段绑定到一个Play控制器中的double.
例如,假设这是我的模型:
case class SavingsGoal(
timeframeInMonths: Option[Int],
amount: Double,
name: String
)
Run Code Online (Sandbox Code Playgroud)
(忽略我使用双倍的钱,我知道这是一个坏主意,这只是一个简化的例子)
我想像这样绑定它:
object SavingsGoals extends Controller {
val savingsForm: Form[SavingsGoal] = Form(
mapping(
"timeframeInMonths" -> optional(number.verifying(min(0))),
"amount" -> of[Double],
"name" -> nonEmptyText
)(SavingsGoal.apply)(SavingsGoal.unapply)
)
}
Run Code Online (Sandbox Code Playgroud)
我意识到number
帮助程序只适用于int,但我认为使用of[]
可能允许我绑定一个double.但是,我得到了一个编译器错误:
Cannot find Formatter type class for Double. Perhaps you will need to import
play.api.data.format.Formats._
Run Code Online (Sandbox Code Playgroud)
这样做没有用,因为API中没有定义双格式化程序.
这只是一个很长的方式来询问在Play中将表单字段绑定到double的规范方法是什么?
谢谢!
编辑:4e6指出了我正确的方向.这是我用他的帮助做的事情:
使用他的链接中的代码段,我将以下内容添加到app.controllers.Global.scala:
object Global {
/**
* Default formatter for the `Double` type.
*/
implicit def doubleFormat: Formatter[Double] = new Formatter[Double] {
override val format = Some("format.real", Nil)
def bind(key: String, data: Map[String, String]) =
parsing(_.toDouble, "error.real", Nil)(key, data)
def unbind(key: String, value: Double) = Map(key -> value.toString)
}
/**
* Helper for formatters binders
* @param parse Function parsing a String value into a T value, throwing an exception in case of failure
* @param error Error to set in case of parsing failure
* @param key Key name of the field to parse
* @param data Field data
*/
private def parsing[T](parse: String => T, errMsg: String, errArgs: Seq[Any])(key: String, data: Map[String, String]): Either[Seq[FormError], T] = {
stringFormat.bind(key, data).right.flatMap { s =>
util.control.Exception.allCatch[T]
.either(parse(s))
.left.map(e => Seq(FormError(key, errMsg, errArgs)))
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的表单映射中:
mapping(
"amount" -> of(Global.doubleFormat)
)
Run Code Online (Sandbox Code Playgroud)
Trp*_*Trp 11
如果您的版本为2.1,则无需使用全局格式.
只需导入:
import play.api.data.format.Formats._
Run Code Online (Sandbox Code Playgroud)
并用作:
mapping(
"amount" -> of(doubleFormat)
)
Run Code Online (Sandbox Code Playgroud)