Saturday, January 3, 2009

Transient properties in a domain class

It is always a common problem to create display values for a view from persistent data. Database amounts don’t have a $ sign and are not formatted, or phone numbers, dates etc. This format conversion can be done in the view with specific tags like g:formatDate or g:formatNumber, or by an own developed tag.

But if there is a specific logic to create a display value this could be done directly in the domain class with a transient variable and the related method.

class Address implements Serializable {

String acctAddr1
String acctAddr2
String acctAddr3

ZipCode zipCode

static transients = ['cityState']

static constraints = {
acctAddr1(nullable:true, blank:true, maxSize:30)
acctAddr2(nullable:true, blank:true, maxSize:30)
acctAddr3(nullable:true, blank:true, maxSize:30)
zipCode(nullable:true)
}

String getCityState() {
if ( zipCode ) {
return zipCode.city + "," + zipCode.state + " " + zipCode.zipCode
else
return ""
}
}
}

class ZipCode implements Serializable {

String zipCode
String state
String city

static constraints = {
zipCode(nullable:false, maxSize:10)
state(nullable:false, maxSize:2)
city(nullable:false, maxSize:30)
}
}

No comments: