I am using Grails 2.4.5 version. I am checking a condition while saving. If my condition matches I am trying to return with a message instead of saving. But it is showing me the message that I want but at the same time it saves the object properties to database.
Here is my code:
@Transactional
def save(AccountHead accountHeadInstance) {
if (!request.method.equals('POST')) {
redirect(action: 'index')
return
}
LinkedHashMap result = new LinkedHashMap()
String outPut
if (accountHeadInstance.id) {
if (accountHeadInstance.id == accountHeadInstance.subParentId) {
result.put(CommonUtils.IS_ERROR, Boolean.TRUE)
result.put(CommonUtils.MESSAGE, "Sorry, Same account can not be parent of it's own")
outPut = result as JSON
render outPut
return
// here should it return, is shows the message ok but saving the object. if I print something after this block it does not execute
}
}
if (accountHeadInstance.hasErrors()) {
def errorList = accountHeadInstance?.errors?.allErrors?.collect{messageSource.getMessage(it,null)}
result.put(CommonUtils.IS_ERROR, Boolean.TRUE)
result.put(CommonUtils.MESSAGE, errorList?.join('\n'))
outPut = result as JSON
render outPut
return
}
accountHeadInstance.hasChild = params.position == CommonUtils.POSITION_FIRST
accountHeadInstance.save flush:true
result.put(CommonUtils.MESSAGE, "Account head saved successfully.")
outPut = result as JSON
render outPut
return
}
Well you are using @Transactional, so any changes to domain object will set that object as dirty, and when the transaction is ended, they will be saved implicitly. To prevent this you can use accountHeadInstance.discard().
However I feel compelled to tell you that your code as several Grails anti-patterns.
Any business logic especially that that uses @Transactional should be moved to service(s), and not done in controllers. Controllers should just be for binding incoming params, routing to servies, and rending results.
While you can use domains as command object binding parameters it is generally not a good idea, from a security standpoint.
Optionally you can do 'Groovy' things like this:
LinkedHashMap result = [:]
result[CommonUtils.IS_ERROR] = Boolean.TRUE)
render result as JSON