我在服务类中有一个创建对象的方法:
def createContent (fileName, description) {
def content = new Content(
fileName:fileName,
description:description,
).save()
}
这两个属性都不可为null。如何将验证错误传递回显示?我尝试过flash.message和render,它们都不能在服务类中工作。我也试过.save(failOnError:true)它显示了一长串错误。
简化一切,看起来应该是这样的。
服务方式:
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验证文档