CHAPTER 7: Rapid Web Development with Grails 337
Delete Action
The delete() action is available, by default, in the edit and show views. Listing 7-25 illustrates the
delete() action of the BookController.
Listing 7-25. The Delete Action of the BookController
def delete(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
}
try {
bookInstance.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code:
'book.label', default: 'Book'), id])
redirect(action: "list")
}
catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message',
args: [message(code: 'book.label', default: 'Book'), id])
redirect(action: "show", id: id)
}
}
The delete() action attempts to retrieve a Book instance and redirects to the list view if it can’t find
one. If an instance is found, a try/catch block is entered, where deletion of the instance is tried. If
the deletion is successful, a message is stored in flash and redirected to the list view. If there is an
exception, a different message is stored in flash and redirected to the show view.
Now that you have seen all the actions generated in the BookController for the Book class, let’s
examine the views generated by static scaffolding for the Book class.
Grails Views
Grails uses Groovy Server Pages (GSP) for its view layer. Grails also uses SiteMesh, the page
decoration framework, to help with page layout. SiteMesh merges each of the .gsp files into a file
called main.gsp to give a consistent look to all the pages. You will begin the generated views with
main.gsp, which can be found in \views\layouts, followed by the four views generated for the Book
class: list.gsp, show.gsp, create.gsp, and edit.gsp. Listing 7-26 illustrates main.gsp.
Listing 7-26. main.gsp
1.<!DOCTYPE html>
2.
3.
4.