아마도 나는 명백한 것을 간과하고있을 것입니다. 그러나 Play 컨트롤러에서 양식 필드를 이중으로 바인딩하는 방법을 알 수 없습니다.재생 : 양식 필드를 이중으로 바인딩 하시겠습니까?
예를 들어, 가정이 내 모델 :
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)
)
}
내가 number
도우미 만의 int 작동 것을 깨달았다 그러나 나는 나를 바인딩 할 수 있습니다 of[]
을 사용하여 생각 : 그리고 지금처럼 결합하고 싶었다 두배. 그러나, 나는이에 컴파일러 오류가 발생합니다 :
Cannot find Formatter type class for Double. Perhaps you will need to import
play.api.data.format.Formats._
는 API에 정의 된 이중 포맷터가 없습니다으로 도움이되지 않습니다 이렇게.
어떻게하면 Play에서 양식 필드를 이중으로 바인딩 할 수있는 표준 방법이 무엇일까?
감사합니다.
편집 : 4e6 올바른 방향으로 나를 가리켰습니다. 여기에 그의 도움을 사용하여 무슨 짓을했는지 :
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)
)
그의 링크에서 미리보기를 사용
을, 나는 app.controllers.Global.scala에 다음을 추가
감사합니다! 그건 완벽하게 작동합니다. 다른 사람들이이 문제에 직면 할 경우를 대비하여 원래의 질문을 솔루션으로 업데이트하겠습니다. – Ryan
이 글을 쓰는 시점에서'doubleFormat'에 대한 링크는 https://github.com/playframework/playframework/blob/b7c414ef11a1a8befa0caa8dbc52fa4e11128a08/framework/src/play/src/main/scala/play/api/data/format/입니다. Format.scala # L132 (프로 팁 : github에서 "y"를 눌러 특정 커밋에 연결된 퍼머 링크를 가져옵니다. "마스터"는 시간이 지남에 따라 움직이기 때문에 마스터 기반 링크는 시간이 지남에 따라 부패합니다.) –