Scala 游戏:将表单字段绑定到双精度?

Scala 游戏:将表单字段绑定到双精度?,scala,playframework-2.0,Scala,Playframework 2.0,也许我忽略了一些显而易见的事情,但我不知道如何在游戏控制器中将表单字段绑定到双精度字段 例如,假设这是我的模型: case class SavingsGoal( timeframeInMonths: Option[Int], amount: Double, name: String ) (忽略我使用double来赚钱,我知道这是个坏主意,这只是一个简单的例子) 我想这样把它绑起来: object SavingsGoals extends Controller { val saving

也许我忽略了一些显而易见的事情,但我不知道如何在游戏控制器中将表单字段绑定到双精度字段

例如,假设这是我的模型:

case class SavingsGoal(
timeframeInMonths: Option[Int],
amount: Double,
name: String
)
(忽略我使用double来赚钱,我知道这是个坏主意,这只是一个简单的例子)

我想这样把它绑起来:

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)

    )

}
我意识到
number
助手仅适用于int,但我认为使用[]的
可能允许我绑定一个double。但是,我得到一个编译器错误:

Cannot find Formatter type class for Double. Perhaps you will need to import
play.api.data.format.Formats._  
这样做没有帮助,因为API中没有定义双格式化程序

这只是一个很长的问题,将表单字段绑定到double-in-Play的规范方法是什么

谢谢

编辑: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)))
      }
    }

}
然后,在我的表单映射中:

mapping(
    "amount" -> of(Global.doubleFormat)
)

实际上,主分支上的
Double
的预定义格式化程序。因此,您应该切换到
2.1-SNAPSHOT
播放版本,或者只复制实现。

如果您的版本为2.1以上,则不需要在全局中使用格式

只需输入:

import play.api.data.format.Formats._
并用作:

mapping(
    "amount" -> of(doubleFormat)
)

谢谢那很好用。我将用我的解决方案更新我的原始问题,以防其他人偶然发现。在撰写本文时,指向
doubleFormat
的链接在这里(专业提示:在github中按“y”可获得与特定提交相关的永久链接。由于“master”会随着时间推移而移动,因此基于master的链接会随着时间推移而腐烂。)