ttt
ttt

Reputation: 4004

Grails domain class fields nullable validator decided by other fields

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?

Upvotes: 2

Views: 553

Answers (1)

dmahapatro
dmahapatro

Reputation: 50275

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)
      }
 }

Upvotes: 4

Related Questions