Reputation: 8671
Say I have a model FsqCheckIn:
case class FsqCheckIn( userId: Int, restaurantId: Int, date: Date, rating: Int )
val myForm = Form( mapping( .... ) )( <Special apply function> )
And a form that a user can fill to check in. My question is,
1) Should I make userId an input of type hidden and then use value from there? Or,
1.1) Add a field 'user' to the Form[T] instance but don't show this to user. Add my own bindFromRequest that will populat this with the current logged in user.
2) Make userId a var in the case class, and then change it's value to the logged in user's id after the form binding succeeds? Or,
3) Is there a way for me to override bindFromRequest
such that I can access request directly? Or,
4) Is there a way for me to access request inside my special apply function
so that I can extract the logged in user id and stamp it on the instance?
I apologize if the question is naive, but I'm very new to MVC and play framework.
Thanks!
EDIT: Added point 1.1
Upvotes: 2
Views: 133
Reputation: 8487
Do not expose anything related to user in a Form, unless you want to manage multiple users within same session. For a user-authnenticated view, you can always figure out which user is logged in. So change:
case class FsqCheckIn( userId: Int, restaurantId: Int, date: Date, rating: Int )
val myForm = Form( mapping( .... ) )( <Special apply function> )
To
case class FsqCheckIn( restaurantId: Int, date: Date, rating: Int )
case class FsqCheckInModel( userId: Int, restaurantId: Int, date: Date, rating: Int )
val myForm = Form( mapping( "restuarantId" -> number, "date" -> nonEmptyText, "rating" -> number) )( FsqCheckIn.apply)(FsqCheckIn.unappy _)
val checkInData = myForm.bindFromRequest.get
// handle validation and date conversion
val user = getUserFromSession
val cq = FsqCheckInModel(user.id, checkInData.restaurantId, checkInData.date, checkInData.rating)
// save to db
Upvotes: 1
Reputation: 11479
1: If you do, the user may change it, which, depending on your use case, might be dangerous
2, 3 & 4: You can create the format inside of your action and have access to the request. You could also build the Form inside a method that takes a request as a parameter if you want to use the same form in multiple actions,
Upvotes: 0