soso
soso

Reputation: 401

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

Upvotes: 1

Views: 170

Answers (1)

Joshua Moore
Joshua Moore

Reputation: 24776

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

Upvotes: 3

Related Questions