Search code examples
grailsgrails-orm

Using field from domain class in constrinsts


How can I set max value for GORM using one field from domain class?

class Test {
    Date start
    Date end

    static constraints = {
        end max: new Date()
        start max: end // <-- here is the problem
    }
}

If I'm doing like above I'm getting error:

No such property: start for class: org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder
groovy.lang.MissingPropertyException: No such property: start for class: org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder
...

I'm using Grails 3.0.4


Solution

  • I believe the requirement is to set the max value of start to be the end date in the runtime. This can only be achieved by using a custom validator as below:

    class Test {
        Date start
        Date end
    
        static constraints = {
            end max: new Date()
            start validator: { val, obj ->
                // val - The value of the property on which the validator is applied
                // obj - this object
                if( val > obj.end ) {
                    // return false
                    // or return max error
                    // or return ['some message to pick up from message bundle']
                }
            }
        }
    }
    

    Refer validator for additional details.