I’m having a problem with an update action inside a Grails controller.
When I submit a form with a password (or its confirmation) changed I’d want to have it validated and if it isn’t well confirmed I should reject the form and warn the user. I’m trying to follow Grails doc instructions on this (http://grails.org/doc/latest/ref/Domain%20Classes/errors.html).
When I change only the password or its confirmation, everything works just fine.
But the problem comes when I change something else then the password in the form, even if the block that validates the password is apparently well executed, the object (userInstance) is still updated. And, not only the other data is persisted, but also is the “bad confirmed” password.
I tried to insert some ‘printlns’ in the example code below to illustrate what happens. I’m using Grails 2.0.0 and debugging in IntelliJ 11.1.3 (if that helps).
I hope to have been clear enough.
Thanks for any answers.
def update() {
...
if (params.password != params.confirmPassword) {
println("This message is correctly printed when passwords differ.")
userInstance.errors.rejectValue('password',
'defaut.password.diff.message',
'Password confirmation is incorrect!')
render(view: "edit", model: [userInstance: userInstance])
return
}
println("This message is correctly NOT printed when passwords differ.")
println("But 'userInstance' object is updated in DB anyways. :( ")
if (!userInstance.save(flush: true)) {
render(view: "edit", model: [userInstance: userInstance])
return
}
flash.message = message(code: 'default.updated.message', args: [message(code: 'utilisateur.label', default: 'Utilisateur'), utilisateurInstance.id])
redirect(action: "show", id: utilisateurInstance.id)
}
I think your
userInstanceis saved because of auto-flushing after successful action. Try to useuserInstance.discard()before your return statement if passwords don’t match. This way you detach this instance from Hibernate and it won’t be saved after an action.