class Person {
String name
Integer age
String street
String email
}
class PersonController {
def save = {
def personInstance = new Person(params)
personInstance.save(flush:true)
}
}
main.gsp
<g:form controller="person" action="save">
<g:textField name="name" />
<g:textField name="age" />
<g:textField name="street" />
<g:textField name="email" />
<g:submitButton name="save" value="Save" />
</g:form>
我必须在 Controller 和gsp页面中都进行哪些修改才能将错误呈现给gsp页面?
最佳答案
将 Controller Action 更改为
def save = {
def personInstance = new Person(params)
if (!personInstance.save(flush: true)) {
render view: 'create', model: [personInstance: personInstance]
return
}
flash.message = "${message(code: 'default.created.message', args: [message(code: 'person.label', default: 'Person'), personInstance.id])}"
redirect action: 'show', id: personInstance.id
}
并将其添加到
<g:form>
之前:<g:hasErrors bean="${personInstance}">
<div class="errors">
<g:renderErrors bean="${personInstance}" as="list" />
</div>
</g:hasErrors>
考虑运行
grails generate-all packagename.Person
并编辑生成的 Controller 和GSP。当然,先将您移开。