Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a method to a domain class

Tags:

grails

groovy

I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).

How do I add the method and how can I then call it from the .gsps?

like image 925
qollin Avatar asked Oct 11 '08 17:10

qollin


3 Answers

To add a method, just write it out like you would any other regular method. It will be available on the object when you display it in your GSP.

def someMethod() {
  return "Hello."
}

Then in your GSP.

${myObject.someMethod()}
like image 183
Hates_ Avatar answered Nov 03 '22 02:11

Hates_


If you want your method to appear to be more like a property, then make your method a getter method. A method called getFullName(), can be accessed like a property as ${person.fullName}. Note the lack of parentheses.

like image 36
John Flinchbaugh Avatar answered Nov 03 '22 03:11

John Flinchbaugh


Consider class like below

class Job {

String jobTitle
String jobType
String jobLocation
String state



static constraints = {

    jobTitle nullable : false,size: 0..200
    jobType nullable : false,size: 0..200
    jobLocation nullable : false,size: 0..200
    state nullable : false


}



def jsonMap () {
    [
         'jobTitle':"some job title",
         'jobType':"some jobType",
         'jobLocation':"some location",
         'state':"some state"
    ]
    }

}

You can use that jsonMap wherever you want. In gsp too like ${jobObject.jsonMap()}

like image 4
Ramesh Avatar answered Nov 03 '22 03:11

Ramesh