0
votes

I am using an older version of grails (1.1.1) and I am working on a legacy application for a government client.

Here is my question (in psuedo form):

I have a domain that is a Book. It has a sub domain of type Author associated with it (1:many relationship). The Author domain has a firstName and lastName field.

def c = Book.createCriteria()
      def booklist = c.listDistinct {
          author {
              order('lastName', 'asc')
              order('firstName', 'asc')
          }
}

Let's say I have a list of fields I want to use for an excel export later. This list has both the author domain call and the title of the column I want to use.

Map fields = ['author.lastName' : 'Last Name', 'author.firstName', 'First Name']

How can I dynamically call the following code--

booklist.eachWithIndex(){
  key, value ->
  println key.fields
}

The intent is that I can create my Map of fields and use a loop to display all data quickly without having to type all of the fields by hand.

Note - The period in the string 'author.lastName' throws an error when trying to output key['author.lastName'] too.

1
Think this is basically the same question as stackoverflow.com/q/4077168/6509tim_yates

1 Answers

1
votes

I don't recall the version of Groovy that came with Grails 1.1, but there are a number of language constructs to do things like this. If it's an old version, some things may not be available - so your mileage may vary.

Map keys can be referenced with quotes strings, e.g.

def map = [:]
map."person.name" = "Bob"

The above will have a key of person.name in the map.

Maps can contain anything, including mixed types in Groovy - so you really just need to work around string escapes or other special cases if you are using more complex keys.

You can also use a GString in the above

def map = [:]
def prop = "person.name"
map."${prop}" = "Bob"

You can also get a map of property/value off of a class dynamically by the properties field on it. E.g.:

class Person { String name;String location; }
def bob = new Person(name:'Bob', location:'The City')
def properties = bob.properties
properties.each { println it }