2
votes

Lots of the Grails controller examples I've seen show you how to add validation code to a command class that gets passed to and from the view, like this:

class RegisterCommand {
    String username
    String email

    static constraints = {
         username blank: false, nullable: false, validator: { value ->
             !User.findByUsername(value) }

         email blank: false, nullable: false, email: true
    }
}

Which is great, but could lead to code duplication if we need to validate User in another controller. So Grails gives you the option of importing validation rules from your domain class, like this -

static constraints = {
    importFrom User
}

So here, my validation rules are being pulled in from my User class.

This really helps with DYR principles, but what if I want to conditionally import validation rules from a domain class? So for example I only want to validate the address fields on the form if someone has checked a box on a form saying that they want to receive a brochure by post. I've tried several variations on this theme, but I can't seem to make it work... Is this possible?

static constraints = {
    importFrom User
    addressCheckbox validator: { value, command -> 
        if (value) {
            importFrom Address
        }
    }
}
1

1 Answers

2
votes

I think it's not working because importFrom works for the constraints builder layer at compile-time, but your validator Closure calls importFrom during the validation phase at runtime.