8

I'm creating a scala application using Play framework and mongoDB. I manage to have the connections up using Leon Play-Salat. I have a model

case class Person(
  id: ObjectId = new ObjectId,
  fname: String,
  mname: String,
  lname: String
)

In my controller I need to map it to a form

val personForm: Form[Person] = Form(

// Defines a mapping that will handle Contact values
mapping(
  "id" -> of[ObjectId],
  "fname" -> nonEmptyText,
  "mname" -> text,
  "lname" -> nonEmptyText     
)(Person.apply)(Person.unapply))

How do I map the ObjectID to the form ? I'm getting error Object not found for the ObjectId.

William
  • 395
  • 1
  • 5
  • 17
  • First of all you have to annotate the `id` field with `@Key("_id")`. Otherwise the field won't be mapped to the mongo's default id field. I think it would help if you pasted the stack trace of the error, because it's not clear when the error occurs. – Rajish Oct 15 '12 at 22:03
  • On the other hand it's not very useful to reveal the `id` field on a form unless it's of a type more human readable than `ObjectID`. – Rajish Oct 15 '12 at 22:09
  • I need the ID for the read and edit function. On the new form the ID should be automatically generated by Mongodb. – William Oct 16 '12 at 03:33

2 Answers2

3

Manage to get it working

val personForm: Form[Person] = Form(
// Defines a mapping that will handle Contact values
mapping(
  "id" -> ignored(new ObjectId),
  "fname" -> nonEmptyText,
  "mname" -> text,
  "lname" -> nonEmptyText     
)(Person.apply)(Person.unapply))

I'm trying to do a CRUD function thus need the ID.

William
  • 395
  • 1
  • 5
  • 17
2

Found using own constructor and deconstructor is better

val personForm: Form[Person] = Form(
  mapping(
    "fname" -> nonEmptyText,
    "mname" -> text,
    "lname" -> nonEmptyText
  )((fname, mname, lname) => Person(new ObjectId, fname, mname, lname))
  ((person: Person) => Some((person.fname, person.mname, person.lname)))      )
William
  • 395
  • 1
  • 5
  • 17