Command Object and hasmany

929 views Asked by At

I'm trying to use the commandObject to validade my data when I submit my form. Can I validate a hasMany relation in commandObject. My cenario is something like this.

Tow simple classes whith hasMany relationship:

class Book{
    String nameBook
}

class Author{
    String nameAuthor
    static hasMany = [books:Book]    
}

Simple commandObject with hasMany that i want to validate when submit form.

@grails.validation.Validateable
class MyValidateCommand{

    String nameAuthor
    static hasMany = [books:Book]


    static constraints = {
        nameAuthor nullable:false
        books nullable:false
    }

}

Ps: I know that this commandObject is wrong, it don't compile. But can I do something like this ???

2

There are 2 answers

1
dmahapatro On BEST ANSWER

hasMany in GORM is used for association in Domain objects. In case of command objects it will be a lucid approach to have different command objects for each domain (for example: AuthorCommand and BookCommand) and the command object would look like:

import org.apache.commons.collections.list.LazyList
import org.apache.commons.collections.functors.InstantiateFactory

//Dont need this annotation if command object 
//is in the same location as the controller
//By default its validateable
@grails.validation.Validateable
class AuthorCommand{
    String nameAuthor
    //static hasMany = [books:Book]

    //Lazily initialized list for BookCommand
    //which will be efficient based on the form submission.
    List<BookCommand> books = 
            LazyList.decorate(new ArrayList(), 
                              new InstantiateFactory(BookCommand.class))

    static constraints = {
        nameAuthor nullable:false
        books nullable:false

        //Let BookCommand do its validation, 
        //although you can have a custom validator to do some 
        //validation here.
    }
}
0
Suganthan Madhavan Pillai On

Not sure why don't you can try like(normal hibernate hasMany declaration)

class MyValidateCommand{

    String nameAuthor
    Set<Book> books= new HashSet<Book>();


    static constraints = {
        nameAuthor nullable:false
        books nullable:false
    }

}