Question

For example, I have a domain class called:

class Employee {
     boolean belongToDepartment
     Department department

     static constraints = {
          department ????
     }
}

I want to write a validator for department which is if the field belongToDepartment is true, department is not null, otherwise department can be null.

I am not sure whether this is make sense?

Was it helpful?

Solution

You can use custom validator on department to check if the boolean flag on the domain object is true and the department value is null. In that case it is a constraint failure, you can return false or an error code depending your need.

static constraints = {
      department nullable: true, validator: {dep, obj ->
          return !(obj.belongToDepartment && !dep)
      }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top