kite
kite

Reputation: 21

Play 2.4 Form field value bind to type java.time.LocalDate

I'm trying to create a form with a field which value type is java.time.LocaDate.

def javaLocalDateForm = Form(single(
  "date" -> of[LocalDate]
))

However, it gives me a compilation error.

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

Tried to import play.api.data.format.Formats._ but compiler still gives me the same error.

Is there any way I can bind form field value to java.time.LocalDate?

Upvotes: 2

Views: 1012

Answers (2)

John
John

Reputation: 5344

I did

class LocalDateFormatter extends play.api.data.format.Formatter[LocalDate] {
  import play.api.data.FormError

  override def bind(key: String, data: Map[String, String]): Either[Seq[FormError], LocalDate] = try{
    Right(
      LocalDate.parse(data(key))
    )
  }
  catch{
    case _:Throwable => Left(Seq(new FormError(key, Seq("error.date"))))
  }

  override def unbind(key: String, value: LocalDate): Map[String, String] = Map(key -> value.toString)
}

and then

// play scala form binders
object UtilsDate{
  import play.api.data.FieldMapping
  def of[DateTime](implicit binder: play.api.data.format.Formatter[DateTime]): FieldMapping[DateTime] = FieldMapping[DateTime]()(binder)
  val formBinder = of(new LocalDateFormatter())
}

in your code you can then use

val myForm = Form(tuple("name" -> nonEmptyText, "date" -> UtilsDate.formBinder))

Upvotes: 0

Shadowlands
Shadowlands

Reputation: 15074

It looks like there are pre-defined Formatters for Joda's LocalDate and java.util.Date, but not (yet) for the Java 8 LocalDate class.

So you could either use the Joda library (for now), or build your own Formatter[java.time.LocalDate], possibly by wrapping around one of these other pre-defined Formatters and converting to the Java LocalDate class.

Upvotes: 2

Related Questions