I've been plowing through play! so far with a few bumps in the learning curve. Right now I am unable to pass flash data from the controller to the view, which at first I thought was a trivial task, or at least it should be.
Here's what I have right now:
I have a main layout: application.scala.html
I have a view that goes in the layout: login.scala.html
and I have my controller and method: UX.authenticate() - I want this to provide flash data to the view depending on the outcome of the login attempt (successful vs fail)
This is my code in my controller method:
def authenticate = Action { implicit request =>
val (email, password) = User.login.bindFromRequest.get
// Validation
// -- Make sure nothing is empty
if(email.isEmpty || password.isEmpty) {
flash + ("message" -> "Fields cannot be empty") + ("state" -> "error")
Redirect(routes.UX.login())
}
// -- Make sure email address entered is a service email
val domain = email.split("@")
if(domain(1) != "example.com" || !"""(\w+)@([\w\.]+)""".r.unapplySeq(email).isDefined) {
flash + ("message" -> "You are not permitted to access this service") + ("state" -> "error")
Redirect(routes.UX.login())
} else {
// Attempt login
if(AuthHelper.login(email, password)) {
// Login successful
val user = User.findByEmail(email)
flash + ("message" -> "Login successful") + ("state" -> "success")
Redirect(routes.UX.manager()).withSession(
session + (
"user" -> user.id.toString
)
)
} else {
// Bad login
flash + ("message" -> "Login failed") + ("state" -> "error")
Redirect(routes.UX.login())
}
}
}
In my login view I have a parameter: @(implicit flash: Flash)
When I try to use flash nothing appears using @flash.get("message")
Ideally I would want to set @(implicit flash: Flash)
in the layout, so that I can flash data from any controller and it will reach my view. But whenever I do that, login view throws errors.
In my login view right now I have this:
def login = Action { implicit request =>
flash + ("message" -> "test")
Ok(views.html.ux.login(flash))
}
What is the ideal way of passing flash data to the view, and are there examples anywhere? The examples on the Play! framework docs do not help whatsoever and are limited to two examples that show no interaction with the view at all (found here at the bottom: http://www.playframework.com/documentation/2.0/ScalaSessionFlash).
Is there an easier alternative? What am i doing wrong? How can I pass flash data directly to my layout view?