Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play! 2 scala: Adding an error to a form in the controller code proper

I have some validation on input data which I really would prefer to handle in the controller code, because:

  1. It only applies in very specific circumstances, so cluttering the verifying function in the form definition would lower code cohesion.
  2. It produces collateral results which I need to use elsewhere in the controller.

What's a clean way form producing a new Form like the one just bound with an additional (field or general) error message in the success branch of Form.fold?

To illustrate, I would like something like the (non-existent) Form.withError method I'm calling here:

val form= myForm.bindFromRequest
form.fold(
  errors => BadRequest(view(errors))
  {
    case(data, button) =>
      button match {
        case Some("save") =>
          val r= costlyFunction(data)
          if (r.isOk) {
            doSomethingWith(r)
            Ok(...)
          }
          else {
            val f= form.withError("my custom error")
            BadRequest(view(f))
          }
        case ...
      }
  }
like image 367
jsalvata Avatar asked Oct 19 '12 13:10

jsalvata


2 Answers

Found it myself:

val f= Form(form.mapping, form.data, 
  Seq(new play.api.data.FormError("error.key", "my error")), form.value)

Apologies for the noise -- leaving it here in case someone else gets stuck as I did.

like image 162
jsalvata Avatar answered Oct 07 '22 19:10

jsalvata


Shorter alternative:

val f= form.withError("error.key", "my error")), form.value)

like image 29
sortega Avatar answered Oct 07 '22 19:10

sortega