我在服务类中有一个创建对象的方法:
def createContent (fileName, description) {
def content = new Content(
fileName:fileName,
description:description,
).save()
}
这些属性都不可为空。如何将验证错误传回显示?我尝试过flash.message和render,两者都不能在服务类中使用。我也试过了 .save(failOnError:真) 这显示了一长串错误。
答案 0 :(得分: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])
}
}
andAction.gsp:
<g:hasErrors bean="${content}">
<g:renderErrors bean="${content}" as="list" />
</g:hasErrors>
一般来说,你应该仔细研究:Grails validation doc