9/06/2009

Customizing Grails/Groovy Drop-Down List

Grails is a powerful framework based on Groovy. Since most of the basic CRUD operations are done by Grails, we sometimes want to edit some of the fields generated in the GSP specially if it is a drop-down list.

There are two ways to edit the drop-down list:
1. By overriding the toString function of the domain
class Student {
String firstName
String lastName

String toString(){
StringBuilder sb = new StringBuilder()
sb.append(firstName)
sb.append(" ")
sb.append(lastName)
return sb.toString()
}
}
Without touching the GSPs, the drop-down list will show the first names and last names of the students and not the default package.domain : id (e.g. Student : 1)

2. By setting the attribute optionValue in g:select tag
optionValue="firstName"
will show only the first names of the students. If you want to show the first names and last names, you may opt to use
optionValue="${{it.firstName + ' ' + it.lastName}}"
Note that character/s can be inserted for each iteration inside single quotes.

2 comments:

  1. Thanks! I was struggling with this. It is not clear in the docs or examples how to control the ddl without writing a custom view

    ReplyDelete