1

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

def createContent (fileName, description) {

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

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

4

1 回答 1

5

简化一切它应该看起来像这样。

服务方式:

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

于 2011-08-05T07:53:09.030 回答