【问题标题】:Grails validation error from service method来自服务方法的 Grails 验证错误
【发布时间】:2011-06-18 18:50:39
【问题描述】:

我在服务类中有一个创建对象的方法:

def createContent (fileName, description) {

    def content = new Content(
        fileName:fileName,
        description:description,
    ).save()
}

这些属性都不能为空。如何将验证错误传回以显示?我试过 flash.message 和 render,这两者都不能在服务类中工作。我也试过 .save(failOnError:true) 它显示了一长串错误。

【问题讨论】:

    标签: service grails-validation


    【解决方案1】:

    简化它应该看起来像这样的所有内容。

    服务方式:

    def createContent (fileName, description) {
        //creating an object to save
        def content = new Content(
            fileName:fileName,
            description:description,
        )
    
        //saving the object
        //if saved then savedContent is saved domain with generated id
        //if not saved then savedContent is null and content has validation information inside
        def savedContent = content.save()
    
        if (savedContent != null) {
            return savedContent
        } else {
            return content
        }
    }
    

    现在在控制器中:

    def someAction = {
        ...
        def content = someService.createContent (fileName, description)
        if (content.hasErrors()) {
            //not saved
            //render create page once again and use content object to render errors
            render(view:'someAction', model:[content:content])
        } else {
            //saved
            //redirect to show page or something
            redirect(action:'show', model:[id:content.id])
        }
    }
    

    还有一些Action.gsp:

    <g:hasErrors bean="${content}">
       <g:renderErrors bean="${content}" as="list" />
    </g:hasErrors>
    

    一般来说,你应该看一下这个:Grails validation doc

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2020-03-06
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      相关资源
      最近更新 更多