Importing Domain Constraints

04 / Apr / 2012 by Imran Mir 0 comments

Following DRY is at the heart of grails. While saving domain objects in our project, we used to copy the domain class constraints to the Command Objects (pretty ugly as it is), until we found that we can import constraints directly from the domain classses using importFrom() method in Grails 2.0
class VenueCO {
String name
String description
Integer someExtraField

String addressLine1
String addressLine2
String city
String state
String zip

static constraints = {
importFrom Venue
importFrom GeographicAddress

someExtraField(nullable: false)

Not only does it import all the constraints from the User and GeographicAddress domain classes and apply them to our command object, but also ignores the constraints that don’t have corresponding properties in the command object.

Other variations of the importFrom() are:
importFrom User, include: ["lastName"]
importFrom User, include: [/.*Name/] // imports all constraints that ended with ‘Name’

Note: It works for grails 2 and above. For others there is a similar concept of shared constraints.

Imran Mir


Leave a Reply

Your email address will not be published. Required fields are marked *