1

There is a way to temporarily disable the beforeInsert event of a specific Domain Class? I need to execute the following steps:

  1. disable the execution of beforeInsert;
  2. Execute a kind of saveAs routine in an object;
  3. re-enable the execution of beforeInsert.

The saveAs routine executes a deep clone in a specific object and creates a new object with the same data. See this answer to understand the clone: How can I duplicate a domain object in Grails?

Reason to disable beforeInsert: Since the object is cloned the code inside beforeInsert doesn't need to be executed when the saveAs routine is executed.

Grails version: 2.5.0

Update

I forgot to mention that I want to avoid change my Domain Class to achieve this behaviour.

Community
  • 1
  • 1
cantoni
  • 2,912
  • 2
  • 17
  • 24
  • Hi @cantoni, didi you find the best solution? – Hemã Vidal Jul 17 '17 at 14:47
  • Unfortunately no, @HemãVidal. My solution was avoid use the beforeInsert event. My saveAs routine is much more important than the code executed in beforeInsert. – cantoni Jul 17 '17 at 18:40
  • I think that is a concept issue: If a .save() method works different in some situations, the controllers must do this action and remove this behavior from domain. – Hemã Vidal Jul 18 '17 at 19:33

1 Answers1

3

You can create a transient Boolean field in the domain class and based on the value of this field you can run your beforeInsert code e.g;

class Person{

Boolean runBeforeInsert = true

static transients = ['runBeforeInsert']

def beforeInsert(){
    if(runBeforeInsert){
         SOME CODE .....
    }
}
}

This might not be the best solution but it's one of the solution.

Uday
  • 619
  • 3
  • 7
  • Thanks @Uday. That is a possible solution, but I'm searching a non-invasive solution. I want to avoid change my domain class. Thanks anyway! – cantoni Oct 15 '15 at 15:48
  • @cantoni IMO there is no other way around, and this might be the less invasive method. – Pablo Pazos Aug 29 '18 at 22:47