Reputation: 1722
I am using Play Framework 2 and want to minimize code duplication when work with forms and validation.
I have controller that renders form and handles form submission:
def create() = Action { implicit request =>
//create form
//DB calls to build comboboxes and tables
Ok(views.html.create(form, ...))
}
def handleCreate() = Action { implicit request =>
createForm.bindFromRequest().fold(
formWithErrors => {
//DB calls to build comboboxes and tables
BadRequest(views.html.create(formWithErrors, ...))
},
obj => {
//other logic
})
}
The problem is in //DB calls to build comboboxes and tables
part. I do not want to duplicate this part. Sure, I can extract it to method and then call it both in create
and handleCreate
methods.
Is it any more elegant way to deal with this code?
Thanks!
Upvotes: 1
Views: 87
Reputation: 11479
This is two separate HTTP calls and since Playframework is stateless there is no direct way to store that data in a server side "session" bound to the same client (unless you implement something like that yourself of course).
What you could do however is use the Play Cache API around the DB calls, make sure the data is immutable and then use the cached data if it still is in the cache when the second call arrives and avoid the extra DB-calls that way. This way it could possibly be shared by more than one client as well, depending on how general the data you read out of the DB is.
Upvotes: 1