Hi guys..
Here I'm going to explain you how to map play form data to a Case class object.
Speciality of this case class is it contains list of object as a field.
Here is my class Course (Course.scala). Assume that Course can contain number of Subjects.
Course ------------> Subjects
Now I'm going to map this object to play form (play.api.mvc.Form). First I have Course and as a field of that I have a List of Subjects. Here inside the Controller This is mapped like this. Only mapping method is displayed
Course ------------> Subjects
case class Course(
id: ObjectId = new ObjectId,
var name: String = "",
var description: String = "",
var price: Int = 0,
var subjects: List[Subject] = List.empty ){
}
case class Subject(
var name: String = "",
var description: String = ""
){}
//This line is for database table creation
//I'm Using MongoDB so table will be created at runtime
object Course extends ModelCompanion[Course, ObjectId] {
val collection = mongoCollection("course") //table name course
val dao = new SalatDAO[Course, ObjectId](collection = collection) {}
}
Now I'm going to map this object to play form (play.api.mvc.Form). First I have Course and as a field of that I have a List of Subjects. Here inside the Controller This is mapped like this. Only mapping method is displayed
def courseForm(implicit request: RequestHeader): Form[Course] = Form(
mapping(
"id" -> nonEmptyText,
"name" -> nonEmptyText,
"description" -> nonEmptyText,
"price" -> nonEmptyText,
"subjects" -> play.api.data.Forms.list
(mapping(
"name" -> nonEmptyText,
"description" -> nonEmptyText)((
name,
description) => Subject(
name = name,
description = description
))(
sub => Some(
sub.name,
sub.description
)))
)((
id,
name,
description,
price,
subjects
) => Course(
id = new ObjectId(id),
name = name,
description = description,
price = toInt,
subjects = subjects.toList
))(
course => Some(
course.id.toString,
course.name,
course.description,
course.price.toString,
course.subjects
)))
Comments