【发布时间】:2012-05-17 22:50:12
【问题描述】:
我有一个如下所示的 Grails 域对象:
class Product {
Boolean isDiscounted = false
Integer discountPercent = 0
static constraints = {
isDiscounted(nullable: false)
discountPercent(range:0..99)
}
我想向discountPercent 添加一个验证器,它只会验证isDiscounted 是否为真,如下所示:
validator: { val, thisProduct ->
if (thisProduct.isDiscounted) {
// need to run the default validator here
thisProduct.discountPercent.validate() // not actual working code
} else {
thisProduct.discountPercent = null // reset discount percent
}
有人知道我该怎么做吗?
【问题讨论】:
-
这正是你的做法,把它放在 discountPercent 属性上,你应该很高兴。什么是行不通的?你有什么例外吗?
-
discountPercent.validate()不存在。 -
validate() 作用于整个域对象而不是单个字段,因此您需要 thisProduct.validate()
-
是的,很抱歉,我浏览了您的实际域对象并假设 discountPercent 是另一个实体。
-
您的意思是
thisProduct.discountPercent = null还是==?不要在验证器中设置值。您可以在beforeInsert或beforeUpdate中设置值。
标签: validation grails groovy grails-orm