David Tinker
David Tinker

Reputation: 9634

What is the best way to add logic to delete() on Grails domain class?

I need to make changes to other domain classes when an instance of a particular domain class is deleted. What is the best way to do this? I don't want to wait until commit or flush so I don't think the "beforeDelete" callback will help. I would like to "override" delete, do some stuff and call super.delete():

class Foo {
    Bar bar
    void delete() {
        if (bar) bar.foo = null
        super.delete() -- this doesn't work
    }
}

Currently I have named "delete" cancel but would like to call it "delete" but then I cannot call the original delete().

Upvotes: 3

Views: 1621

Answers (2)

R. Valbuena
R. Valbuena

Reputation: 474

I haven't tried overriding GORM methods myself, but this might give some insight on what's involved:

"Overloading" standard GORM CRUD methods

I would put the "delete" logic in a service and call that instead:

class FooService {

    def deleteInstance(foo) {
        if (foo?.bar) {
            foo.bar.foo = null
            // might have to call foo.bar.save() here
            // then foo.bar = null
        }
        foo.delete()
    }

}

Upvotes: 1

OverZealous
OverZealous

Reputation: 39560

To add to what @sbglasius said, here's the link to the docs on GORM events

Complete example:

class Foo {
    Bar bar

    def beforeDelete() {
        if(bar) {
            bar.foo = null
        }
    }
}

Upvotes: 5

Related Questions