Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD


This is Part 3 of 9 for the Catalyst tutorial.

Tutorial Overview

  1. Introduction

  2. Catalyst Basics

  3. Basic CRUD

  4. Authentication

  5. Authorization

  6. Debugging

  7. Testing

  8. AdvancedCRUD

  9. Appendicies


This part of the tutorial builds on the fairly primitive application created in Part 2 to add basic support for Create, Read, Update, and Delete (CRUD) of Book objects. Note that the 'list' function in Part 2 already implements the Read portion of CRUD (although Read normally refers to reading a single object; you could implement full read functionality using the techniques introduced below). This section will focus on the Create and Delete aspects of CRUD. More advanced capabilities, including full Update functionality, will be addressed in Part 8.

TIP: Note that all of the code for this part of the tutorial can be pulled from the Catalyst Subversion repository in one step with the following command:

    svn checkout
    IMPORTANT: Does not work yet.  Will be completed for final version.


Our initial attempt at object creation will utilize the "URL arguments" feature of Catalyst (we will employ the more common form-based submission in the sections that follow).

Include a Create Action in the Books Controller

Edit lib/MyApp/Controller/ and enter the following method:

    =head2 url_create
    Create a book with the supplied title, rating, and author
    sub url_create : Local {
        # In addition to self & context, get the title, rating, & 
        # author_id args from the URL.  Note that Catalyst automatically 
        # puts extra information after the "/<controller_name>/<action_name/" 
        # into @_
        my ($self, $c, $title, $rating, $author_id) = @_;
        # Call create() on the book model object. Pass the table 
        # columns/field values we want to set as hash values
        my $book = $c->model('MyAppDB::Book')->create({
                title  => $title,
                rating => $rating
        # Add a record to the join table for this book, mapping to 
        # appropriate author
        $book->add_to_book_authors({author_id => $author_id});
        # Note: Above is a shortcut for this:
        # $book->create_related('book_authors', {author_id => $author_id});
        # Assign the Book object to the stash for display in the view
        $c->stash->{book} = $book;
        # This is a hack to disable XSUB processing in Data::Dumper
        # (it's used in the view).  This is a work-around for a bug in
        # the interaction of some versions or Perl, Data::Dumper & DBIC.
        # You won't need this if you aren't using Data::Dumper (or if
        # you are running DBIC 0.06001 or greater), but adding it doesn't 
        # hurt anything either.
        $Data::Dumper::Useperl = 1;
        # Set the TT template to use
        $c->stash->{template} = 'books/create_done.tt2';

Notice that Catalyst takes "extra slash-separated information" from the URL and passes it as arguments in @_. The url_create action then uses a simple call to the DBIC create method to add the requested information to the database (with a separate call to add_to_book_authors to update the join table). As do virtually all controller methods (at least the ones that directly handle user input), it then sets the template that should handle this request.

Include a Template for the url_create Action:

Edit root/src/books/create_done.tt2 and then enter:

    [% # Use the TT Dumper plugin to Data::Dumper variables to the browser   -%]
    [% # Not a good idea for production use, though. :-)  'Indent=1' is      -%]
    [% # optional, but prevents "massive indenting" of deeply nested objects -%]
    [% USE Dumper(Indent=1) -%]
    [% # Set the page title.  META can 'go back' and set values in templates -%]
    [% # that have been processed 'before' this template (here it's for      -%]
    [% # root/lib/site/html and root/lib/site/header).  Note that META on    -%]
    [% # simple strings (e.g., no variable interpolation).                   -%]
    [% META title = 'Book Created' %]
    [% # Output information about the record that was added.  Note use  -%]
    [% # of 'first' to only list the first author (if > 1 author).      -%] 
    <p>Added book '[% book.title %]' by '[% book.authors.first.last_name %]'
    with a rating of [% book.rating %].</p>
    [% # Provide a link back to the list page                                    -%]
    [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
    <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
    [% # Try out the TT Dumper (for development only!) -%]
    Dump of the 'book' variable:
    [% Dumper.dump(book) %]

The TT USE directive allows access to a variety of plugin modules (TT plugins, that is, not Catalyst plugins) to add extra functionality to the base TT capabilities. Here, the plugin allows Data::Dumper "pretty printing" of objects and variables. Other than that, the rest of the code should be familiar from the examples in Part 2.

IMPORTANT NOTE As mentioned earlier, the view class created by TTSite redefines the name used to access the Catalyst context object in TT templates from the usual c to Catalyst.

Try the url_create Feature

If the application is still running from before, use Ctrl-C to kill it. Then restart the server:

    $ script/

Note that new path for /books/url_create appears in the startup debug output.

TIP: You can use script/ -r to have the development server auto-detect changed files and reload itself (if your browser acts odd, you should also try throwing in a -k). If you make changes to the TT templates only, you do not need to reload the development server (only changes to "compiled code" such as Controller and Model .pm files require a reload).

Next, use your browser to enter the following URL:


Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by 'Stevens' with a rating of 5." along with a dump of the new book model object. You should also see the following DBIC debug messages displayed in the development server log messages:

    INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
    INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'

If you then click the "Return to list" link, you should find that there are now six books shown (if necessary, Shift-Reload your browser at the /books/list page).


Although the url_create action in the previous step does begin to reveal the power and flexibility of both Catalyst and DBIC, it's obviously not a very realistic example of how users should be expected to enter data. This section begins to address that concern.

Add Method to Display The Form

Edit lib/MyApp/Controller/ and add the following method:

    =head2 form_create
    Display form to collect information for book to create
    sub form_create : Local {
        my ($self, $c) = @_;
        # Set the TT template to use
        $c->stash->{template} = 'books/form_create.tt2';

This action simply invokes a view containing a book creation form.

Add a Template for the Form

Open root/src/books/form_create.tt2 in your editor and enter:

    [% META title = 'Manual Form Book Create' -%]
    <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
      <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
      <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
      <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
    <input type="submit" name="Submit" value="Submit">

Note that we have specified the target of the form data as form_create_do, the method created in the section that follows.

Add Method to Process Form Values and Update Database

Edit lib/MyApp/Controller/ and add the following method to save the form information to the databse:

    =head2 form_create_do
    Take information from form and add to database
    sub form_create_do : Local {
        my ($self, $c) = @_;
        # Retrieve the values from the form
        my $title     = $c->request->params->{title}     || 'N/A';
        my $rating    = $c->request->params->{rating}    || 'N/A';
        my $author_id = $c->request->params->{author_id} || '1';
        # Create the book
        my $book = $c->model('MyAppDB::Book')->create({
                title   => $title,
                rating  => $rating,
        # Handle relationship with author
        $book->add_to_book_authors({author_id => $author_id});
        # Store new model object in stash
        $c->stash->{book} = $book;
        # Avoid Data::Dumper issue mentioned earlier
        # You can probably omit this    
        $Data::Dumper::Useperl = 1;
        # Set the TT template to use
        $c->stash->{template} = 'books/create_done.tt2';

Test Out The Form

If the application is still running from before, use Ctrl-C to kill it. Then restart the server:

    $ script/

Point your browser to http://localhost:3000/books/form_create and enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an author ID of 4. You should then be forwarded to the same create_done.tt2 template seen in earlier examples. Finally, click "Return to list" to view the full list of books.

Note: Having the user enter the primary key ID for the author is obviously crude; we will address this concern with a drop-down list in Part 8.


Turning out attention to the delete portion of CRUD, this section illustrates some basic techniques that can be used to remove information from the database.

Edit root/src/books/list.tt2 and update it to the following (two sections have changed: 1) the additional '<th>Links</th>' table header, and 2) the four lines for the Delete link near the bottom).

    [% # This is a TT comment.  The '-' at the end "chomps" the newline.  You won't -%]
    [% # see this "chomping" in your browser because HTML ignores blank lines, but  -%]
    [% # it WILL eliminate a blank line if you view the HTML source.  It's purely   -%]
    [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
    [% # Provide a title to root/lib/site/header -%]
    [% META title = 'Book List' -%]
    [% # Display each book in a table row %]
    [% FOREACH book IN books -%]
        <td>[% book.title %]</td>
        <td>[% book.rating %]</td>
          [% # First initialize a TT variable to hold a list.  Then use a TT FOREACH -%]
          [% # loop in 'side effect notation' to load just the last names of the     -%]
          [% # authors into the list.  Note that we are making a bogus assignment to -%]
          [% # the 'xx' vbl to avoid printing the size of the list after each push.  -%]
          [% tt_authors = [ ];
             xx = tt_authors.push(author.last_name) FOREACH author = book.authors %]
          [% # Now use a TT 'virtual method' to display the author count             -%]
          ([% tt_authors.size %])
          [% # Use another TT virtual method to join the names with comma separators -%]
          [% tt_authors.join(', ') %]
          [% # Add a link to delete a book %]
          <a href="[% Catalyst.uri_for('delete/') _ %]">Delete</a>
    [% END -%]

The additional code is obviously designed to add a new column to the right side of the table with a Delete "button" (for simplicity, links will be used instead of full HTML buttons).

Add a Delete Action to the Controller

Open lib/MyApp/Controller/ in your editor and add the following method:

    =head2 Delete 
    Delete a book
    sub delete : Local {
        # $id = primary key of book to delete
        my ($self, $c, $id) = @_;
        # Search for the book and then delete it
        $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
        # Set a status message to be displayed at the top of the view
        $c->stash->{status_msg} = "Book deleted.";
        # Forward to the list action/method in this controller

This method first deletes the book with the specified primary key ID. However, it also removes the corresponding entry from the book_authors table. Note that delete_all was used instead of delete: whereas delete_all also removes the join table entries in book_authors, delete does not.

Then, rather than forwarding to a "delete done" page as we did with the earlier create example, it simply sets the status_msg to display a notification to the user as the normal list view is rendered.

The delete action uses the context forward method to return the user to the book list. The detach method could have also been used. Whereas forward returns to the original action once it is completed, detach does not return. Other than that, the two are equivalent.

Another alternative to forward would be to use $c->response->redirect($c->uri_for('/books/list')). The forward and redirect operations differ in several important respects that stem from the fact that redirects cause the client browser to issue an entirely new HTTP request. In doing so, this results in a new URL showing in the browser window. And, because the stash information is reset for every request, the "Book deleted" message would not be displayed.

Try the Delete Feature

If the application is still running from before, use Ctrl-C to kill it. Then restart the server:

    $ script/

Then point your browser to http://localhost:3000/books/list and click the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book deleted" status message should display at the top of the page, along with a list of the six remaining books.


Kennedy Clark,

Please report any errors, issues or suggestions to the author.

Copyright 2006, Kennedy Clark, under Creative Commons License (