简体   繁体   English

如何对grails上的域字段应用新验证

[英]How to apply new validation for a domain field on grails

I've this domain: 我有这个域名:

class Foo {
  static hasMany=[
    bars: Bar
  ]

  String name

  static constraints = {
    name(blank: false, unique: true)
  }
}

after inserting values to database I added another validation for bars 在向数据库插入值后,我添加了另一个条形验证

bars(nullable: false, validator: {value, object ->
            if(value.isEmpty()){
               return['bars.empty.validation.error']
            }
        })

now when i try to update Foo instances that were saved with no bars save is complaining on field bars : 现在,当我尝试更新保存没有条形保存的Foo实例时,在字段bars上抱怨:

Field error in object 'Foo' on field 'bars': rejected value [[Bar : (unsaved)]]

My question is how can I update Foo instances with no bars 我的问题是如何更新没有bars Foo实例

You could change your custom validation to only apply to instances that don't have an id associated with them (indicating they are being inserted and not updated). 您可以将自定义验证更改为仅应用于没有与其关联的id实例(表示它们正在插入且未更新)。 Such as this: 比如这样:

bars(nullable: false, validator: {value, object ->
  if (object?.id) return // don't apply to previously saved instance.
  if(value.isEmpty()){
    return['bars.empty.validation.error']
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM