score:8
If you look in the documentation for Session and Flash scopes you'll see this code snippet:
def save = Action {
Redirect("/home").flashing(
"success" -> "The item has been created"
)
}
Now, compare that to your use of the flash scope:
flash + ("message" -> "Login successful") + ("state" -> "success")
The issue with this usage is that flash is immutable, you can't reassign it. Moreover, with your usage here you're actually creating a new flash variable, it just isn't being used.
If you had modified that slightly to become:
implicit val newFlash = flash + ("message" -> "Login successful") + ("state" -> "success")
Redirect(...)
It would've worked. However, the preferred usage is to use the .flashing()
method on your result. This method comes from play.api.mvc.WithHeaders, a trait that is mixed in to play.api.mvc.PlainResult which the various result methods (Ok, Redirect, etc.) inherit from.
Then, as shown in the documentation, you can access the flash scope in your template:
@()(implicit flash: Flash) ...
@flash.get("success").getOrElse("Welcome!") ...
edit: Ah, okay. I've reviewed your sample code and now I see what you're trying to do. I think what you're really looking for is the canonical way of handling form submissions. Review the constraint definitions here in the documentation and I think you'll see there's a better way to accomplish this. Essentially you'll want to use the verifying
method on the tuple backing your form so that bindFromRequest
will fail to bind and the validation errors can be passed back to the view:
loginForm.bindFromRequest.fold(
formWithErrors => // binding failure, you retrieve the form containing errors,
BadRequest(views.html.login(formWithErrors)),
value => // binding success, you get the actual value
Redirect(routes.HomeController.home).flashing("message" -> "Welcome!" + value.firstName)
)
score:5
Wanted to add one more thing to this discussion, to help people avoid this error:
could not find implicit value for parameter flash: play.api.mvc.Flash
I know a lot of this is redundant, but there's a technicality at the end that stole half of my workday and I feel I can help people out with. Appending .flashing(/* your flash scoped info */), such as:
Redirect(routes.ImageEditApp.renderFormAction(assetId)).
flashing("error" -> "New filename must be unused and cannot be empty.")
... does defines the implicit "flash" variable that you can use in your template, if you have a "base" template that you want to handle flash scope with (such as errors), single usage of the base template is easy, since you already have the implicit flash variable defined via .flashing() ... This is an example of one of my "includes" of a base template.
@views.html.base("Editing: "+asset.id, scripts = Some(scripts),
extraNav = Some(nav))
You do not have to pass the "flash" variable to the base template. It's an implicit. The base template still has to define it. The parameters for my base template is this:
@(title: String, stylesheets: Option[Html] = None,
scripts: Option[Html] = None,
extraNav: Option[Html] = None)(content: Html)(implicit flash: Flash)
Yeah, I know a lot of that is unnecessary, but this is a real world example I'm copy n' pasting from. Anyway, it's likely you need to have other templates that use your base template, and you do not always use .flashing() to load them. Since you're surely loading these using Controllers, if you forget to start your Action for each with implicit request => such as:
def controllerMethodName() = Action { implicit request =>
then the "flash" implicit will not be defined. Then when that template tries to include your base template, you'll be flummoxed because you don't have the default flash implicit variable defined, while the base template requires it. Hence that error.
So again, the fix.. go to all of your controller methods, and make sure you put in that implicit request => !
Source: stackoverflow.com
Related Query
- How to pass flash data from controller to view with Play! framework
- How to pass Request Header from Main view to Partial View in Play framework
- Passing data from controller to view in scala / play framework
- How to send POST data with an AngularJS form to Play Framework Controller
- How to execute tests on the argument that a controller passes to the view in Play Framework
- Scala - parse JSON data from API with ScalaJson Play Framework
- How to create JSON output from a combined group of composite classes with Play framework
- How to map multiple Futures and pass them as arguments to a view using Play with Scala
- How can I render the current controller and action name in the view of Play Framework 2?
- Play Framework 2 / How to ensure years with 4 digits from form's input date?
- How to send an Akka actor shutdown message from controller in play framework
- Best practices to separate business logic from the Controller to the Model layer with Play framework + Scala + Slick
- How to test a controller in Play Framework with a functional test
- Play Framework compilation error when passing List object from controller to view
- How to obtain flash scope - Play Framework with Scala, maximum arguments in template
- How to pass array of array (list of list) to view in play framework 2.x?
- How to pass custom objects from Play Framework filters to controllers?
- how to instantiate a controller class with injection in play framework 2.5.x
- Play framework Scala - how to pass text from a textInput in a form into a function
- How to use IntelliJ with Play Framework and Scala
- How to render JSON response in Play framework v2.0 (latest build from GIT)
- How to improve the error message readability returned from JsError.toFlatJson or JsError.toJson in Play framework 2.x?
- Which is best data access options available for Play framework with Scala and PostgreSQL?
- How to schedule an hourly job with Play Framework 2.1?
- How to create a global variable with Play Framework 2.0
- How do I get Intellij IDEA 12.0 to work with Play Framework 2.1.0 app and Scala 2.10.0?
- How to print @ symbol in HTML with play framework (scala)
- How to run Play Framework 2.2.0 with -feature option
- How to show images using Play framework and Scala in the view page
- How do I unit test a controller in play framework 2 scala
More Query from same tag
- How could I automatically update and display time(every 10 sec) using Lift Comet
- Best practice to create SparkSession object in Scala to use both in unittest and spark-submit
- How to parse an XML node having key-value pair using spark scala
- F-Bounded Polymorphic return types in Scala?
- Efficiently returning the next larger value of a non-existing key in scala's sorted collections?
- Extract type from kind
- How to pass an object to a method in Scala
- Why does this Scala actor code require blocking to work?
- What is the most succinct way to redirect HTTP requests to HTTPS in Scalatra?
- Add multiple array values to a list is possible in scala?
- How to check if spark actually parallelizes the job?
- Use Scala to Find The Most Common 'uncommon' word in keys
- Better way to change the content of a monadic type than `map`
- Error while saving Random Forest Model in spark cluster scala
- Optimizing cartesian product using keys in spark
- How to decode null to empty string in Circe
- higher kinded types and WrappedString
- Anonymous function in Scala, error depending on notation
- scala implicit class: inherit all members of parameter
- Scala Pattern Matching Enigma
- Spark: Accumulators does not work properly when I use it in Range
- Scala pattern matching with manifest
- Error:scalac: error while loading Specification, Scala signature Specification has wrong version expected: 5.0 found: 4.1 in Specification.class
- Filter Dataframe on columns defined in a list
- Scala Play - How to Modify Cookie setting value before response goes out?
- How to delete an entire data frame in Spark(SCALA)?
- ScalikeJDBC, raw SQL failing to map or return a valid result set
- Chisel Passing Enum type as IO
- Merging n rows of a dataframe containing duplicate values
- Jenkins static code analysis for sbt project