Last updated by dserodio 4 years ago

Tips and Tricks in Grails

Showing a GSP's generated Groovy code

Add showSource to the URL of the grails controller to see the generated Groovy code from the gsp page. Example:

http://localhost:8080/App/Controller/list?param1=value1&showSource=true

This feature only works when executing Grails within the "development" environment. More details here http://www.nabble.com/spillGroovy-argument...-tf2298639.html#a6386846

Quick Tip on Markup Builder example is from a Domain object (Book) that contains enum's if you have only simple datatypes then "render as XML" works just fine

String toXML() {
  StringWriter buffer = new StringWriter()
  def xml = new MarkupBuilder(buffer)
  xml.book() {
    id(this.id)
    author(this.authorName)
    pagecount(pagecount:this.pagecount)
  }
  return buffer.toString() + "\\n"
}
Keep in mind that the difference between author and pagecount looks like this in the xml
<book>
  <id>222</id>
  <author>Toddecus</author>
  <pagecount pagecount='99' />
</book>
You can see that the pagecount is much more terse but may present challenges on parsing.

Quick Tip on parsing say a Rest service that returns the XML above: This assumes you used an XMLSlurper to parse the text into a GPathResult

static Book fromXML(GPathResult bookXML)
{ 
 def book = new Book()
 book.id = Integer.parseInt(bookXML.id.text())
 book.author = bookXML.author.text()
 book.pagecount = Integer.parseInt(bookXML.pagecount.@pagecount.text())
 return book
}

Pay special attention to the use of the "at" symbol to get access to the property on the field as opposed to the field contents.

If you really cared about terse XML in your REST service you might even do this:

String toXML() {
  StringWriter buffer = new StringWriter()
  def xml = new MarkupBuilder(buffer)
  xml.book(id: this.id, author:this.authorName, pagecount:this.pagecount){}
  return buffer.toString() + "\\n"
}
Which would result in XML like this:
<book id='222' author='Toddecus' pagecount='99' />
doesn't help much if your domain object contains a set of sub elements though :)

Enum usage

If you want to use a Enum with a "value" String attribute (a pretty common idiom) in a <select> element, try this:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

final String value

Rating(String value) { this.value = value }

String toString() { value } String getKey() { name() } }

Then add optionKey="key" to your <g:select /> tag. Credit: Gregg Bolinger