Grails: nested command objects
Asked Answered
I

2

10

In my grails app I have an outer command object that contains a list of other command objects:

public class OuterCommand {

    List<InnerCommand> innerCommands = ListUtils.lazyList([], FactoryUtils.instantiateFactory(InnerCommand))
}

class InnerCommand {
    String code
    Long id
    String value

    static constraints = {
        code(nullable: false, blank: false)
        value(nullable: false, blank: false)
    }
}

The rather unusual instantiation of innerCommands is based on this advice. However, I find that if I call validate() on an instance of OuterCommand, the validation does not seem to validate the contained instances of InnerCommand.

Is it possible to nest command objects and have the entire graph of command objects validated when validate() is called on the outermost object?

Infrequency answered 9/12, 2009 at 18:7 Comment(0)
I
9

I got this working by following these steps:

Make the inner command object validatable since it is not getting instantiated like a normal command object. There are two ways to do this, with the @org.codehaus.groovy.grails.validation.Validateable annotation, or with the grails config parameter grails.validateable.classes

Adding a custom validator for innerCommands to OuterCommand

static constraints = {
    innerCommands(validator: {val, obj ->
        // 'attributes.validation.failed' is the key for the message that will
        // be shown if validation of innerCommands fails
        return val.every { it.validate() } ?: ['attributes.validation.failed'] 
    })
}
Infrequency answered 9/12, 2009 at 21:14 Comment(1)
See old.nabble.com/… for discussion.Insignificant
V
0

I don't think that Domain Objects in a Command or nested Commands get validated by default, you would have to write a validator that loops through the innerCommands and validates them all.

static constraints = {
    innerCommands(validator:{val,obj ->
        //validate and merge errors from each innerCommand
    })
}

You'll probably have to handle the Errors object and merge it all the results together, but its not too difficult.

Vesperal answered 9/12, 2009 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.