我在 Grails 控制器中的更新操作有问题。
当我提交一个更改了密码(或其确认)的表单时,我希望对其进行验证,如果没有得到很好的确认,我应该拒绝该表单并警告用户。我正在尝试按照 Grails 文档说明进行操作 (http://grails.org/doc/latest/ref/Domain%20Classes/errors.html)。
当我只更改密码或其确认时,一切正常。
但是当我更改其他内容然后更改表单中的密码时,问题就出现了,即使验证密码的块显然执行得很好,对象 (userInstance) 仍然会更新。并且,不仅其他数据被持久化,而且是“错误确认”密码。
我试图在下面的示例代码中插入一些 'printlns' 来说明会发生什么。我正在使用 Grails 2.0.0 并在 IntelliJ 11.1.3 中调试(如果有帮助的话)。
我希望已经足够清楚了。
感谢您提供任何答案。
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)
}
Run Code Online (Sandbox Code Playgroud)
我认为您userInstance的保存是因为成功操作后自动刷新。userInstance.discard()如果密码不匹配,请尝试在 return 语句之前使用。通过这种方式,您可以将此实例与 Hibernate 分离,并且不会在操作后保存。
| 归档时间: |
|
| 查看次数: |
715 次 |
| 最近记录: |