I'm using Grails 1.3.7. In开发者_运维技巧 a Grails project, I want to add a function ajaxupdate to the default scaffolded Controller, which does exactly the same job as the update function, but returns JSON data with the list of the eventual errors.
def ajaxupdate = {
String retMessage = ""
List errMessageList = []
def ${propertyName} = ${className}.get(params.id)
if (${propertyName}) {
${propertyName}.properties = params
if (!${propertyName}.hasErrors() && ${propertyName}.save(flush: true)) {
retMessage = "\${message(code: 'default.updated.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), ${propertyName}.id])}"
}
else {
// Add errors in errMessageList
}
}
else {
errMessageList.add("\${message(code: 'default.not.found.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), params.id])}")
}
render(contentType: "text/json") {
answer(
message:retMessage,
errors:errMessageList)
}
}
If you're asking how to get the errors list, you can access Errors like
errMessageList = ${propertyName}.errors.allErrors.collect {g.message(error:it).encodeAsHTML()}
精彩评论