Grails: custom validator based on previous field value

I am trying to create a special validator for the variable 'amount' in my domain class, so the new value should be 0.50 greater than the previous one.

For example, suppose the previous value was 1.0, the next time the value should be at least: [previous value + 0.50] or more.

Thank you in advance

+3
source share
2 answers

You can try to read domainEntity.getPersistentValue('amount').

EDIT: ... in a custom validator, for example:

class Bid { 
  Double amount 
  ...
  static constraints = { amount(validator: { double a, Bid b -> 
    def oldValue = b.getPersistentValue('amount')
    a > oldValue + 0.5 ? true : "Amount $a should be at least ${oldValue  + 0.5}" }) 
  }
}
+4
source

thanks Victor Sergienko, but I'm modifying your code a bit

class Bid { 
  Double amount 
  ...
  static constraints = { amount(validator: { double a, Bid b -> 
    Bid tempBid = Bid.get(b.id)
    def oldValue = tempBid.getPersistentValue('amount')
    a > oldValue + 0.5 ? true : "Amount $a should be at least ${oldValue  + 0.5}" }) 
  }
}

The difference in this line is:

Bid tempBid = Bid.get(b.id)
def oldValue = tempBid.getPersistentValue('amount')

, b.getPersistentValue('amount') null, grails - 2.4.3

0

Source: https://habr.com/ru/post/1792255/


All Articles