CHAPTER 7: Rapid Web Development with Grails 335
If there are errors, the user is redirected to the create() action. For this redirect to the create()
action, params was assigned to the bookInstance’s property, as mentioned in the create() action
earlier in Listing 7-20. If there are no errors, the show view is rendered with the newly created
instance.
Show Action
Listing 7-22 illustrates the show() action of the BookController.
Listing 7-22. The Show Action of the BookController
def show(Long id) {
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
}
[bookInstance: bookInstance]
}
The show() action expects an id parameter. The first line of the show() action calls the Book.get( )
method to retrieve the Book referred to by the id parameter. If no Book instance exists with the id
passed in, an error message is stored in the flash scope, and the user is redirected to the list view.
If a Book instance is found with the id passed in, it is returned in a Map with the key of bookInstance,
and the show() action will render the show view.
Edit Action
Listing 7-23 illustrates the edit() action of the BookController.
Listing 7-23. The Edit Action of the BookController
def edit(Long id) {
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
}
[bookInstance: bookInstance]
}
The edit() action loads the necessary data that will be used during editing and passes it to the edit
view. The edit() action is very much the same as the show() action. The name of the edit() action,
edit, is used to render the edit view.