Up: Chapter 4

4.5 Field Errors

In the prior examples, we displayed an error to the user. However, we didn’t tell the user what field resulted in the error. Let’s be a little more granular about error reporting.
First, let’s look at the HTML:
fielderror.html
<div id="main" class="lift:surround?with=default&at=content">
  <div>
    Let's get granular about error messages
  </div>
  
  <div>
    <div class="lift:FieldErrorExample?form=post">
      Name: <input name="name"><br>
      Age: <span class="lift:Msg?id=age&errorClass=error">error</span>
      <input name="age" id="the_age" value="0"><br>
      <input type="submit" value="Submit">
    </div>
  </div>
</div>
​
This HTML is different. Note: Age: <span class="lift:Msg?id=age&errorClass=error">error</span>. We mark an area in the markup to put the error message.
Let’s look at our snippet code which is very similar to Stateful.scala with a small, but important difference:
FieldErrorExample.scala
package code
package snippet
​
import net.liftweb._
import http._
import common._
import util.Helpers._
import scala.xml.NodeSeq
​
/**
 * A StatefulSnippet like Stateful.scala
 */
class FieldErrorExample extends StatefulSnippet {
  private var name = ""
  private var age = "0"
  private val whence = S.referer openOr "/"
​
  def dispatch = {case _ => render}
​
  def render =
    "name=name" #> SHtml.text(name, name = _) &
    "name=age" #> SHtml.text(age, age = _) &
    "type=submit" #> SHtml.onSubmitUnit(process)
  
  // like Stateful
  private def process() =
    asInt(age) match {
      // notice the parameter for error corresponds to
      // the id in the Msg span
      case Full(a) if a < 13 => S.error("age", "Too young!")
      case Full(a) => {
        S.notice("Name: "+name)
        S.notice("Age: "+a)
        S.redirectTo(whence)
      }
      
      // notice the parameter for error corresponds to
      // the id in the Msg span
      case _ => S.error("age", "Age doesn't parse as a number")
    }
}
The key difference is: case Full(a) if a < 13 => S.error("age", "Too young!"). Note that we pass "age" to S.error and this corresponds to the id in the Msg snippet in markup. This tells Lift how to associate the error message and the markup.
But there’s a better way to do complex forms in Lift: LiftScreen.
Up: Chapter 4

(C) 2012 David Pollak