Search code examples
validationgrailsgrails-ormnullable

Grails: Constraints: Database to allow nulls, but forms may not be blank


I have a domain object called OurCompany and I'd like to be able to deliberately insert a row mostly full of nulls. When a user fills in a form though, I'd like to validate it and not allow blanks.

class OurCompany {

    static constraints = {        
        enterpriseName blank:false, nullable:true
    }

    String enterpriseName

    static belongsTo = [measurement:Measurement]

}

When I create the empty row in the database, I turn off validation and it works fine.

ourCompany = new OurCompany();
measurement.addToOurCompany(ourCompany).save(validate:false);

Later, when I update the row, the validation is ignored and the record saves even though there is a null / blank value.

def ourCompany = loadOrCreateOurCompany();
def industrySectors = loadIndustrySectors();

bindData (ourCompany, params)

ourCompany.validate()
if (ourCompany.hasErrors()) {
    ourCompany.errors.allErrors.each {
        println(it)
    }
} else {            
    ourCompany.save();
}

How do I tell grails that I'd like the DATABASE to accept nulls, but when validating, not allow nulls or blanks?


Solution

  • That's what Command Objects are for