Mik378 Mik378 - 1 month ago 9
Scala Question

Play Framework 2.1 / form mapping with complex objects

Play Framework documentation for Scala shows a sample mapping a form to a case class implicitly:

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

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


We notice that only primitive values are used in this unique sample.

How about if we make this alteration:

case class Car(brandName: String)

case class User(name: String, car: Car)


Moreover, let's assume that the form returns the
User
's name (String) and a
carId
(String)

val userForm = Form(
mapping(
"name" -> text,
"car" -> carRepository.findById(nonEmptyText) // concept I wish
)(User.apply)(User.unapply)
)


Is there any way to instantiate a car at this wished line with some
carId
provided for example by the form and ensuring also that the
carId
is not an empty
String
?

Answer

For first part of your question, documentation also shows Nested values:

case class Car(brandName: String)
case class User(name: String, car: Car)

val userForm = Form(
  mapping(
    "name" -> text,
    "car" -> mapping(
        "brandName" -> text
    )(Car.apply)(Car.unapply)
  )(User.apply, User.unapply)
)
Comments