grails - 如果 grails 中验证失败则返回同一页面

标签 grails redirect

我正在 Controller 中进行一些表单验证(使用插件),并在验证通过/失败时设置一个名为 status =true/false 的 bool 变量

此验证发生在 update 操作中,并且请求来自 edit.gsp。 如果验证失败,我希望控件返回到 edit.gsp。我可以实现这一点吗?或者我必须单独创建 update.gsp 并复制 edit.gsp 的内容,以显示编辑后的表单值以及 update.gsp 上的错误消息页?我希望避免将所有其他参数传递到后端并返回仅进行 1 个字段清理检查。
它看起来应该类似于 javascript,但实际上后端验证在错误时重定向到同一页面。 我该如何实现这一目标? 验证成功后,我将重定向到 manageTemplate.gsp

问候, 提前致谢

最佳答案

根据您如何使用插件触发验证,我认为最简单的方法是在域对象上编写自定义验证器。更多信息:http://grails.org/doc/latest/ref/Constraints/validator.html

如果您不想(或不能)走这条路线,您可以手动检查 Controller 中插件的验证。它基本上与脚手架 Grails 页面/ Controller 使用的模式相同。

在 Controller 中,您可以使用插件进行验证,如果域实例未验证,则将用户重定向回编辑操作并包含“参数”。这样,所有字段仍将像以前一样填充。

来自脚手架 Grails Controller 的更新片段(针对名为 Tag 的域对象):

    // ...
    // Code above here just gets the domain object to edit (tagInstance in this case)
    // and checks that the object hasn't be updated in the meantime

    tagInstance.properties = params

    // params have been applied to object, you can now do custom validation

    def status = extraValidationService.validate( tagInstance ) // or however you run the validation

    if ( !status ) {
       flash.message = "Did not pass custom validation"
       render(view: "edit", model: [tagInstance: tagInstance]) // Back to same edit page (field values maintained)
       return        
    }

    // Everything below here is unchanged

    if ( !tagInstance.save( flush: true, failOnError: false ) ) {
        render(view: "edit", model: [tagInstance: tagInstance])
        return
    }

    flash.message = message(code: 'default.updated.message', args: [message(code: 'tag.label', default: 'Tag'), tagInstance.id])
    redirect(action: "show", id: tagInstance.id) // This is where you redirect to the manageTemplate action.gsp

这不会在验证失败的字段上突出显示验证。为此,您可以使用自定义验证器方法,或者您可以(我从未这样做过)能够手动“告诉”域对象哪些字段验证失败以及原因。

关于grails - 如果 grails 中验证失败则返回同一页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9810820/

相关文章:

unit-testing - Grails域映射通过 “none”无法在单元测试中使用

hibernate - SELECT bla1,bla2 FROM foo的条件

url - 使用 URL 重定向站点阻止 Telegram 链接预览

jsf - faces-redirect和返回按钮导致其他链接无法正常工作

grails - 我的规范有什么问题?

grails - 无法获得级联保存,无法在嵌入式类引用上删除以正常工作

php - 如何在 .htaccess 文件中指定范围以重定向 url

asp.net-mvc - FormsAuthentication.RedirectFromLoginPage() 如何工作?

mysql - 如何在 GORM 表架构更改后让系统正常工作?

redirect - Github 页面 URL 重定向到旧的自定义域