strobe
strobe

Reputation: 529

How to set Options values to form mapping in Play 2?

I would like to map Option value to form but without ignored. For instance:

case class Message(Id: Option[Int], name: String, description: Option[String])

val messageForm: Form[Message] = Form(
  mapping(
    "id"          -> ignored(Option(0)),
    "name"        -> nonEmptyText(minLength = 4, maxLength = 140),
    "description" -> text
)(Message.apply)(Message.unapply))
          ^

type mismatch;
found   : (Option[Int], String, Option[String]) => Message
required: (Option[Int], String, String)         => ?

Ignored "id" value used successful, but 'text' produce errors with apply function. How correctly do than? need I to write custom form constraints for Option[String]?

Upvotes: 3

Views: 1326

Answers (1)

senia
senia

Reputation: 38045

You could transform Mapping[String] to Mapping[Optional[String]] using optional method like this:

val messageForm: Form[Message] = Form(
  mapping(
    "id"          -> ignored[Option[Int]](None),
    "name"        -> nonEmptyText(minLength = 4, maxLength = 140),
    "description" -> optional(text)
)(Message.apply)(Message.unapply))

Note that you could use None to indicate that there is no value in id field.

Upvotes: 8

Related Questions