简体   繁体   中英

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 :

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

My question is how can I update Foo instances with no bars

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). 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']
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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