Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails global constraints

In version 1.2, Grails introduced global constraints. I tried adding the following to Config.groovy

grails.gorm.default = {

    constraints {
        notBlank(nullable:false, blank:false)
    }
}

Then using it in one of my domain classes

static constraints = {
    email(email: true, unique: true, shared: 'notBlank')
}

But when I save a user with a null e-mail address, no errors are reported, why?

Thanks, Don

like image 468
Dónal Avatar asked Jan 23 '23 15:01

Dónal


2 Answers

I've never tried to make global constraints, but I can tell you that if you want to mark a field as not blank and not nullable you don't need to create a new constraint at all, just add this to your domain class:

static constraints = {
    email(blank:false)
}

Of course if you're expecting an exception on save you won't get one - you need to test the object after calling save() or validate() as demonstrated in this domain class:

class Contact {
    static constraints = {
        name(blank:false)
    }
    String name
}

and its test case:

import grails.test.*

class ContactTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testNameConstraintNotNullable() {
        mockDomain Contact
        def contact = new Contact()
        contact.save()
        assertTrue contact.hasErrors()
        assertEquals "nullable", contact.errors["name"]
    }
}

If you do want exceptions on save, you can add this setting in your Config.groovy:

grails.gorm.save.failOnError = true

I found it to be quite useful in development.

HTH

PS

To use a constraint you've defined you'd need to add this to your domain class:

static constraints = {
    email(shared:"myConstraintName")
}

But be warned, you can't test the constraint in a unit test as you would the built in ones as the config will not have been read.

like image 114
Dave Bower Avatar answered Feb 05 '23 03:02

Dave Bower


If you want the default constraint applied to all properties is should be:

grails.gorm.default = {
    constraints {
        '*'(nullable:false, blank:false)
    }
}

If you want to name the constraint, you would apply it to your domain class property of email using the shared key:

static constraints = {
    email(email: true, unique: true, shared: "notBlank")
}

The default in grails is to not allow null properties, so blank:false is all you really need (i.e., global default you defined in this case is not needed).

like image 42
John Wagenleitner Avatar answered Feb 05 '23 03:02

John Wagenleitner