Java Reference
In-Depth Information
Update Action
The
update()
action is called when changes from the edit view are submitted. Listing 7-24 illustrates
the
update()
action of the
BookController
.
Listing 7-24. The Update Action of the BookController
def update(Long id, Long version) {
def bookInstance = Book.get(id)
if (!bookInstance) {
flash.message = message(code: 'default.not.found.message',
args: [message(code: 'book.label', default: 'Book'), id])
redirect(action: "list")
return
}
if (version != null) {
if (bookInstance.version > version) {
bookInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: 'book.label', default: 'Book')] as Object[],
"Another user has updated this topic while you were editing")
render(view: "edit", model: [bookInstance: bookInstance])
return
}
}
bookInstance.properties = params
if (!bookInstance.save(flush: true)) {
render(view: "edit", model: [bookInstance: bookInstance])
return
}
flash.message = message(code: 'default.updated.message', args: [message(code:
'book.label', default: 'Book'), bookInstance.id])
redirect(action: "show", id: bookInstance.id)
}
The
update()
action tries to retrieve a
Book
instance with the
id
parameter. The
id
is provided from
the edit view. If an instance is found, an optimistic concurrency check is performed. If there are no
errors, all the values from the edit view are assigned to the appropriate property of the
Book
instance,
including any necessary data conversion.
bookInstance.properties = params
If both of those steps are successful, a “success” message is stored in
flash
, and the user is
directed to the show view. If either step fails, a “failure” message is stored in flash, and the user is
directed back to the edit view.