HowTo use JSON forms

From LiftWiki

Jump to: navigation, search

Hi,

Lift has a marvelous Ajax and JSON support. So far we were able to submit Ajax forms, process them in a functional way and return the response. Now it is possible to use JSonHandler support to process forms.

SHtml contain overloaded jsonForm functions that facilitates the forms json-ification:

Here is an example:

JSONForm snippet

class JSONForm {

  
  def show(html: Group): NodeSeq = {
    jsonForm(json, html) // we just wrap the snippet content into relevant form code
  }

  import JsCmds._
  object json extends JsonHandler {
    def apply(in: Any): JsCmd =
      SetHtml("json_result", in match {
        case j @ JsonCmd("processForm", _, p: Map[String, _], _) => {
          // process the form or whatever
          println("Cars = " + urlDecode(p("cars").toString))
          println("Name = " + urlDecode(p("name").toString))
          <b>{p}</b>
        }
        case x => <b>Problem... didn't handle JSON message {x}</b>
      })
  }

  def head = <head>{Script(json.jsCmd)}</head>
}

This is a small xhtml page

<lift:surround with="default" at="content">
	<lift:JSONForm.head />
	<lift:JSONForm.show>
		<input type="text" name="name" />
		<br />
		<input type="text" name="value" />
		<br />
		<input type="radio" name="vehicle" value="Bike" />
		<input type="radio" name="vehicle" value="Car" />
		<input type="radio" name="vehicle" value="Airplane" />
		<br />
		<select name="cars">
			<option value="volvo">Volvo</option>
			<option value="saab">Saab</option>
			<option value="opel">Opel</option>
			<option value="audi">Audi</option>
		</select>
		<button type="submit">Submit</button>
	</lift:JSONForm.show>
	<div id="json_result"></div>
</lift:surround>

Notes: - In order to use json forms you need to include in your page jlift.js which can be achieved by changing the head function for:

 def head = <head><script type="text/javascript" src="/classpath/jlift.js" /> {Script(json.jsCmd)}</head>

The js file is created by lift and is not required to be in your files.

Personal tools
search|search