修改并验证 Grails 域对象而不保存它,可以通过以下步骤实现:
Person
的域对象,您可以在 Person
类中添加验证规则:class Person {
String name
Integer age
static constraints = {
name blank: false, maxSize: 50
age min: 0, max: 120
}
}
validate()
方法来验证域对象。validate()
方法会返回一个布尔值,指示域对象是否通过验证。例如,在 PersonController
中:def update(Long id, Long version) {
def personInstance = Person.get(id)
if (!personInstance) {
flash.message = "Person not found with id $id"
redirect action: 'list'
return
}
if (version != null) {
if (personInstance.version > version) {
personInstance.errors.rejectValue('version', 'person.optimistic.locking.failure',
[message(code: 'person.optimistic.locking.failure', default: "Another user has updated this Person while you were editing")] as Object[],
"Another user has updated this Person while you were editing")
render view: 'edit', model: [personInstance: personInstance]
return
}
}
personInstance.properties = params
if (!personInstance.validate()) {
render view: 'edit', model: [personInstance: personInstance]
return
}
personInstance.save flush: true
flash.message = "Person updated successfully"
redirect action: 'show', id: personInstance.id
}
在上述示例中,personInstance.validate()
会验证 Person
域对象的属性,并在不满足验证规则的情况下返回 false
。如果验证失败,将重新显示编辑视图,而不会将更改保存到数据库中。
edit.gsp
视图中,您可以使用 <g:hasErrors>
标签来显示验证错误。例如:<g:hasErrors bean="${personInstance}">
<div class="alert alert-danger">
<g:renderErrors bean="${personInstance}" as="list" />
</div>
</g:hasErrors>
这将在验证失败时显示错误消息,指示用户更正输入。
通过以上步骤,您可以修改并验证 Grails 域对象,而不保存它。
领取专属 10元无门槛券
手把手带您无忧上云