私はこのフォームマッピングを持っています:
val myElement = Form(
mapping(
"title" -> nonEmptyText,
"schedule" ->
tuple("startSchedule" -> jodaDate("dd/MM/yyyy HH:mm"),
"endSchedule" -> jodaDate("dd/MM/yyyy HH:mm"))
.verifying(MyValidator().checkForEndScheduleConsistency("error.schedule")),
)(MyElement.apply)(MyElement.unapply)
)
MyElement
クラス:
case class MyElement(title: String, schedule: (Datetime, Datetime))
MyValidator
クラス:
def checkForEndScheduleConsistency(errorMsg: String) =
Constraint[(DateTime, DateTime)]("constraint.schedule", errorMsg) {
schedule =>
MyDomainValidator().checkForEndScheduleConsistency(schedule._1, schedule._2, Messages(errorMsg)) match {
case Success(s) => Valid
case Failure(f) => Invalid(ValidationError("custom error string from `f`"))
}
}
要件:オブジェクトschedule.endSchedule
によってスケジュールが矛盾している場合は、フィールド (タプルの要素)にエラー メッセージを関連付ける必要がありMyValidator
ます。
ただし、必要な要素 (startSchedule
とendSchedule
) の両方をメソッドで使用できるようにするために、入れ子になったタプルの という名前の要素にメソッドを直接checkForEndScheduleConsistency
適用することはできません。代わりに、コード スニペットに示すように、変数を含めるためにタプル全体に 1 つを適用する必要があります。verifying
endSchedule
startSchedule
欠点は、エラーがマップされているのではendSchedule
なくschedule
(HTML フォームでは何も表されていない) ため、矛盾したスケジュールが表示されたときに画面に何も表示されないことです。
したがって、この「回避策」を使用して、Form
のwithError
方法を使用して要件を達成する必要があります。
def create = Action {
implicit request =>
myForm.bindFromRequest.fold(
myFormWithErrors => {
myFormWithErrors.error("schedule") match { //check for the presence of potential schedule error
case Some(e) => {
BadRequest(views.html.create_element("Create an element", myFormWithErrors.withError("schedule.endSchedule", Messages("error.schedule"))))
}
case _ => BadRequest(views.html.create_element("Create an element", myFormWithErrors))
}
},
myForm => {
treatSubmittedMyForm(myForm)
}
)
}
=>非常に醜く、乾燥防止。
タプルに適用する方法はありますverifying
か?それにもかかわらず、ネストされたタプルの要素にエラーメッセージを適用しますか? 私の場合、endSchedule
.