Reputation: 4337
I have a play2.5 scala project and I want to pass a global message from the controller for example in case an error happened. How can I achieve this without using the form global message.
For example in the handleRegisterError method I would like to throw an global error message that would show on the top off the page.
What is the best approach to this?
I'm using twirl templates
def registerUser = Action.async { implicit request =>
RegisterForm.form.bindFromRequest.fold(
formWithErrors => {
Future.successful(BadRequest(views.html.register(formWithErrors)))
},
formData => {
registerUserService.registerUser(formData).map{ insertedId =>
Ok(views.html.index(""))
}
.recover {
case cause => handleRegisterError(cause)
}
})
}
def handleRegisterError(cause: Throwable)(implicit req: RequestHeader) : Result = {
cause match {
case dae: DataAccessException =>
//add an error message here
BadRequest(views.html.register(RegisterForm.form))
case _ =>
BadRequest(views.html.register(RegisterForm.form))
}
}
Upvotes: 0
Views: 176
Reputation: 401
You should be able to use Redirect
with the message attached to Flash
scope
Redirect(views.html.register(RegisterForm.form)).flashing("error" -> "Oops, you've got an error")
Add RequestHeader
as a template parameter and render the error message if defined.
@(form: Form[RegisterForm])(implicit request: RequestHeader)
@request.flash.get("error").map { message =>
<div>@message</div>
}
Upvotes: 1