我在提交表单时尝试使用 commandObject
来验证我的数据。我可以验证 commandObject
中的 hasMany 关系吗?我的场景是这样的。
两个简单的类
,其中有很多关系:
class Book{
String nameBook
}
class Author{
String nameAuthor
static hasMany = [books:Book]
}
简单的commandObject
与hasMany,我想在提交表单时进行验证。
@grails.validation.Validateable
class MyValidateCommand{
String nameAuthor
static hasMany = [books:Book]
static constraints = {
nameAuthor nullable:false
books nullable:false
}
}
Ps:我知道这个commandObject是错误的,它无法编译。但我可以做这样的事情吗???
最佳答案
GORM 中的
hasMany
用于 Domain 对象中的关联。对于命令对象,为每个域使用不同的命令对象(例如:AuthorCommand
和 BookCommand
)将是一种清晰的方法,命令对象如下所示:
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.
}
}
关于grails - 命令对象和 hasman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382346/