Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a global form error to Play 2.0 form to indicate optimistic lock failure

I have a simple model object:

case class Region(id: String, revision: Option[String], name: String)

object Region {        
    // Returns Some(region) if successful, None if revision doesn't match the latest
    // in the data store
    def insertOrUpdate(region: Region): Promise[Option[Region]]
}

In my controller I want to do something like this but I don't know how to indicate the lock failure in the response. I would like to add a global form error but can't see how from the API.

def update(id: String) = Action {
    implicit request => regionForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.regions.edit(formWithErrors)),        
        region => Async{
            Region.insertOrUpdate(region).map{
                _ match {
                    case None => {
                    // How do I add a global form error indicating there were server side changes detected
                        BadRequest(views.html.regions.edit(regionForm.fill(region))
                    }
                    case Some(r) => Redirect(views.html.regions.index).flashing(("success", "Update successful")
            }
        }
    )
}
like image 879
Brian Avatar asked Jan 05 '13 11:01

Brian


1 Answers

For Play 2.0.4

A global error is in reality an error without key (see globalErrors method).

There is no helper to add an error, but you can do it by yourself, with something like that:

regionForm.fill(region)
  .copy(errors = FormError("", "Your Error Message") +: errors)

For Play 2.1

You can use the withGlobalError method:

regionForm.fill(region)
  .withGlobalError("Your error message")))
like image 50
Julien Lafont Avatar answered Sep 17 '22 05:09

Julien Lafont