Mikey
Mikey

Reputation: 4742

Grails: how to perform action when a Domain Class property is set in GORM

Is there any way to make a Domain Class setter have imperative actions. This is what I wish would work, is it possible some other way?

Domain Class:

Class ExampleDomain {
  BigDecimal someNumber
  def setSomeNumber = {setVal ->
    println "Today is a good day to be the number: ${setVal}"
  }

}

Can I only bind events on onUpdate and things like that or is there a way to have changes to the Java object drive events?

For example:

def thisThing = new ExampleDomain(someNumber:3.0) //prints "Today is a good day to be the number: 3.0"
thisThing.someNumber = 5.8  //prints "Today is a good day to be the number: 5.8"
thisThing.save()  //prints nothing

Is that possible behaviour?

Upvotes: 1

Views: 303

Answers (1)

david
david

Reputation: 2587

You can do this by defining getter/setter methods instead of closures:

Class ExampleDomain {
  BigDecimal someNumber

  void setSomeNumber(someNumber) {
    println "Today is a good day to be the number: ${someNumber}"
    this.someNumber = someNumber
  }

  BigDecimal getSomeNumber() {
    someNumber
  }
}

works for

//prints "Today is a good day to be the number: 5.8"
new ExampleDomain().someNumber = 5.8  

Upvotes: 3

Related Questions