user1980875
user1980875

Reputation:

Clarifications on how to map complex objects using Play 2.1 form bindings

This is the example taken from the documentation:

import play.api.data._
import play.api.data.Forms._

case class User(name: String, age: Int)

val userForm = Form(
  mapping(
    "name" -> text,
    "age" -> number
  )(User.apply)(User.unapply)
)

val anyData = Map("name" -> "bob", "age" -> "18")
val user: User = userForm.bind(anyData).get

What is the Map instance (named anyData) doing here? I mean...is it used as a means of providing a default value for the user (in case the mapping done by the form fails)? or does it have any other purposes?

Upvotes: 0

Views: 181

Answers (1)

Vinicius Miana
Vinicius Miana

Reputation: 2067

The anyData is just showing how the Map must be filled in order to be processed by the userForm and return the result value tuple (String,Int) with name and age.

The form generates a tuple from a Map and these lines just show how to do it.

val anyData = Map("name" -> "bob", "age" -> "18")
val user: User = userForm.bind(anyData).get

On a real application you will get the map implicitly from the request which contains the data filled in the HTML form by executing:

val user: User = loginForm.bindFromRequest.get

Upvotes: 1

Related Questions