David P
David P

Reputation: 1

Saving parents when children has errors Groovy/Grails

I have a parentObject with children, the children have other children. I need to maintain the validation of 'children2' in 'children1' because I need the idx of 'children1' to show a good message. But, when I save parentObjet, it saves normally even when 'children2' has errors.

I have a domain (the project is more complex than that, but I'll summarize it)

DomainParent(){
   List DomainChildren;

   static hasMany = [domainChildren: DomainChildren];
}
DomainChildren(){
   List AnotherDomainChild

   static hasMany = [anotherDomainChild: AnotherDomainChild];

   static constraints = {
     anotherDomainChild(nullable:true, validator: {data, obj, errors->
        if(data ! = null && data.size() > 0){
          for(int i = 0; i < obj.rateioPontoArmazenamento.size(); i++){
              def anotherDomainChildInstance = obj.anotherDomainChild.get(i)
              if (anotherDomainChildInstance.qntd == null)
{errors.rejectValue("anotherDomainChild[${i}].qntd", "obj.qntd.validator.invalid1", [(obj.idx + 1)] as Object[], "")}
          }
        }
     })
   }
}
AnotherDomainChild(){
   BigDecimal qntd;
}

in the controller, i have something like..

@Transactional(readOnly = false)
def update(Long id, Long version) {
...
DomainParent.withTransaction{status-> service.save(domainInstance)}
...
}

println domainInstance.errors

and service is something like

@Transactional
def save(instance) throws PersistenceGroovyException {
        if(!instance.save(flush: true)){
            throw new PersistenceGroovyException (instance, 'default.save.erro.exception')
        }
    }

As you can see, i have a println in controller after save. if i try to save a parentDomain with AnotherDomainChild.qntd = null, it saves successfully but the parentDomain still with errors after save -\> "obj.qntd.validator.invalid1". I need to keep the validation on DomainChildren because i need idx to show a good message to users. How can i break the save process correctly in the domains? i cant understand why it saves with a children object even when it has an error.

Upvotes: 0

Views: 30

Answers (0)

Related Questions