Question

In order to have a validation on my domain class object, I need to get all the relevant fields that I need to have validation on.
The exact fields I need are those who I defined by myself in my domain class and not those who GORM did.

I need to know how can I get those fields ?
I mean, how to I get all the fields without 'id', 'version' and all other GORM generated fields.
Thanks!

Was it helpful?

Solution

There are several things you can do.

If you have a domain class like this:

// grails-app/domain/com/demo/Person.groovy
class Person {
    String firstName
    String lastName

    // notice that only firstName is constrained, not lastName
    static constraints = {        
        firstName matches: /[A-Z].*/
    }
}

You can interrogate the persistentProperties property to get a list of all persistent properties:

def person = new Person()
def personDomainClass = person.domainClass
// this will not include id and version...
def persistentPropertyNames = personDomainClass.persistentProperties*.name

assert persistentPropertyNames.size() == 2
assert 'firstName' in persistentPropertyNames
assert 'lastName' in persistentPropertyNames

If you wanted to do the same sort of thing but don't have an instance of the Person class to interrogate you can do something like this:

def personDomainClass = grailsApplication.getDomainClass('com.demo.Person')
// this will not include id and version...
def persistentPropertyNames = personDomainClass.persistentProperties*.name

assert persistentPropertyNames.size() == 2
assert 'firstName' in persistentPropertyNames
assert 'lastName' in persistentPropertyNames

You could also get the keys out of the constraints Map:

// this will include both firstName and lastName,
// even though lastName is not listed in the constraints
// closure.  GORM has added lastName to make it non
// nullable by default.
// this will not include id and version...
def constrainedPropertyNames = Person.constraints.keySet()

assert constrainedPropertyNames.size() == 2
assert 'firstName' in constrainedPropertyNames
assert 'lastName' in constrainedPropertyNames

I hope that helps.

OTHER TIPS

The constraints property on a domain class instance gives you a list of ConstrainedProperty objects representing the properties that are listed in the constraints block in the domain class, in the order they are listed (see the bottom of this documentation page).

static constraints = {
  prop2()
  prop1(nullable:true)
  prop3(blank:true)
}

So provided you have mentioned every property in the constraints block then you can use

myObj.constraints.collect { it.propertyName }

to get a list of the property names (in the above example you'd get [prop2, prop1, prop3]).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top