Search code examples
grailsgrails-domain-classgrails3beforeupdategrails3.2.0

Find isDirty() for children elements


I'm using Grails 3.2:

class Training{
    boolean clientChanged = false
    static transients = ['clientChanged']

    static hasMany = [clients:User]
    //...

    def beforeUpdate(){
        clientChanged = this.isDirty('clients')
    }

    def afterUpdate(){
        if(clientChanged && section.clients)
            numberOfAbsentClients = section.clients.size() - (clients.size()?:0)
    }
}

isDirty() is not working for hasMany associations. how can I handle it?


Solution

  • Collections are handled slightly differently. Depending on whether you are using Hibernate or one of the other implementations of GORM you need to check if the collection is a org.hibernate.collection.spi.PersistentCollection (for Hibernate) or a org.grails.datastore.mapping.collection.PersistentCollection (for MongoDB/Neo4j/etc)

    The PersistentCollection interface has a isDirty() method that you can use to check if the association was changed. So something like:

     if(clients instanceof PersistentCollection && clients.isDirty()) { 
         ...
     }
    

    Will do it.