加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 播放:将表单域绑定到双面?

发布时间:2020-12-16 19:03:24 所属栏目:安全 来源:网络整理
导读:也许我只是忽略了一些明显的东西,但是我无法弄清楚如何将一个表单域绑定到一个播放控制器中的一个. 例如,假设这是我的模型: case class SavingsGoal(timeframeInMonths: Option[Int],amount: Double,name: String) (不知道我用了一双钱,我知道这是一个坏主
也许我只是忽略了一些明显的东西,但是我无法弄清楚如何将一个表单域绑定到一个播放控制器中的一个.

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

case class SavingsGoal(
timeframeInMonths: Option[Int],amount: Double,name: String
)

(不知道我用了一双钱,我知道这是一个坏主意,这只是一个简单的例子)

我想绑定它就像这样:

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)

    )

}

我意识到数字助手只适用于int,但我认为使用[]可能会允许我绑定一个double.但是,我得到一个编译器错误:

Cannot find Formatter type class for Double. Perhaps you will need to import
play.api.data.format.Formats._

这样做没有帮助,因为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,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)
)

解决方法

实际上,there is预定义格式化程序为Double在主分支上.所以你应该切换到2.1-SNAPSHOT播放版本或只是复制实现.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读