Sunday, October 5, 2008

Drop Down Lists in the Lift framework

Ok, I need to add a select box to a web page. This should be farely easy in any modern web framework, but I'm using Lift, a new framework written in Scala.

Anyway, Lift has a singleton object (a common concept in Scala) with numerous utility functions for generating HTML elements (it's SHtml). This object has the select, selectObj, and select_* methods, which can generate a simple select box.

The first one was easy, it is designed to display name/value pairs of strings. The second one was much more difficult (due to my inexperience with Scala).

As I discovered, scala has a type called Option which allows for a an optional argument or value without having to check for null or deal with null exceptions.

Lift has it's own option like type called Can. As far as I can see, this provides similar functionality and is used throughout the framework.

In this particular instance the selectObj method was expecting a list of objects/values; a default value which is actually a Can holding the value or Empty; and a function to execute when the form is submitted.

After researching (David Pollak and Programming In Scala) I finally discovered how to use the selectObj method and more importantly learned about the Option type in scala and the Can type in Lift.

Adding a dop down list with objects and having that object returned to you is not so easy in most frameworks that I have delt with in the past (Java and .NET). Here is the code that I ended up writing, which is super cool:


1 def displayCourseList():NodeSeq = {
2
3 val c1 = new Course("111", "item 1")
4 val c2 = new Course("222", "item 2")
5
6 val courses = List((c1, c1.name), (c2, c2.name))
7
8 <span>
9 { SHtml.selectObj[Course](courses, Full(course1), course => print(course.number) }
10 </span>
11
12 }

Total Pageviews

Labels