3 Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial Part 3: Basic CRUD
9 This is B<Part 3 of 9> for the Catalyst tutorial.
11 L<Totorial Overview|Catalyst::Manual::Tutorial>
17 L<Introduction|Catalyst::Manual::Tutorial::Intro>
21 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
29 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41 L<Testing|Catalyst::Manual::Tutorial::Testing>
45 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49 L<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
57 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 C<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.
59 B<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:
61 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
62 IMPORTANT: Does not work yet. Will be completed for final version.
66 =head1 FORMLESS SUBMISSION
68 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).
71 =head2 Include a Create Action in the Books Controller
73 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
77 Create a book with the supplied title, rating and author
81 sub url_create : Local {
82 # In addition to self & context, get the title, rating & author_id args
83 # from the URL. Note that Catalyst automatically puts extra information
84 # after the "/<controller_name>/<action_name/" into @_
85 my ($self, $c, $title, $rating, $author_id) = @_;
87 # Call create() on the book model object. Pass the table
88 # columns/field values we want to set as hash values
89 my $book = $c->model('MyAppDB::Book')->create({
94 # Add a record to the join table for this book, mapping to
96 $book->add_to_book_authors({author_id => $author_id});
97 # Note: Above is a shortcut for this:
98 # $book->create_related('book_authors', {author_id => $author_id});
100 # Assign the Book object to the stash for display in the view
101 $c->stash->{book} = $book;
103 # This is a hack to disable XSUB processing in Data::Dumper
104 # (it's used in the view). This is a work-around for a bug in
105 # the interaction of some versions or Perl, Data::Dumper & DBIC.
106 # You won't need this if you aren't using Data::Dumper (or if
107 # you are running DBIC 0.06001 or greater), but adding it doesn't
108 # hurt anything either.
109 $Data::Dumper::Useperl = 1;
111 # Set the TT template to use
112 $c->stash->{template} = 'books/create_done.tt2';
115 Notice that Catalyst takes "extra slash-separated information" from the URL and passes it as arguments in C<@_>. The C<url_create> action then uses a simple call to the DBIC C<create> method to add the requested information to the database (with a separate call to C<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.
118 =head2 Include a Template for the C<url_create> Action:
120 Edit C<root/src/books/create_done.tt2> and then enter:
122 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
123 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
124 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
125 [% USE Dumper(Indent=1) -%]
127 [% # Set the page title -%]
128 [% META title = 'Book Created' %]
130 [% # Output information about the record that was added. Note use -%]
131 [% # of 'first' to only list the first author (if > 1 author). -%]
132 <p>Added book '[% book.title %]' by '[% book.authors.first.last_name %]'
133 with a rating of [% book.rating %].</p>
135 [% # Provide a link back to the list page -%]
136 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
137 <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
139 [% # Try out the TT Dumper -%]
141 Dump of the 'book' variable:
142 [% Dumper.dump(book) %]
145 The TT C<USE> directive allows access to a variety of plugin modules (we are talking TT plugins here, not Catalyst plugins) to add extra functionality to the base TT capabilities. Here, the plugin allows L<Data::Dumper|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.
147 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view class created by TTSite redefines the name used to access the Catalyst context object in TT templates from the usual C<c> to C<Catalyst>.
150 =head2 Try the C<url_create> Feature
152 If the application is still running from before, use C<Ctrl-C> to kill it. Then restart the server:
154 $ script/myapp_server.pl
156 Note that new path for C</books/url_create> appears in the startup debug output.
158 B<TIP>: You can use C<script/myapp_server.pl -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 C<-k>). If you make changes to just the TT templates, you do not need to reload the development server (only changes to "compiled code" such as Controller and Model C<.pm> files require a reload).
160 Next, use your browser to enter the following URL:
162 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
164 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:
166 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
167 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
169 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 C</books/list> page).
173 =head1 MANUALLY BUILDING A CREATE FORM
175 Although the C<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.
178 =head2 Add Method to Display The Form
180 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
184 Display form to collect information for book to create
188 sub form_create : Local {
191 # Set the TT template to use
192 $c->stash->{template} = 'books/form_create.tt2';
195 This action merely invokes a view containing a book creation form.
198 =head2 Add a Template for the Form
200 Open C<root/src/books/form_create.tt2> in your editor and enter:
202 [% META title = 'Book Create' -%]
204 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
206 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
207 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
208 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
210 <input type="submit" name="Submit" value="Submit">
213 Note that we have specified the target of the form data as C<form_create_do>, the method created in the section that follows.
216 =head2 Add Method to Process Form Values and Update Database
218 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to save the form information to the databse:
220 =head2 form_create_do
222 Take information from form and add to database
226 sub form_create_do : Local {
229 # Retrieve the values from the form
230 my $title = $c->request->params->{title} || 'N/A';
231 my $rating = $c->request->params->{rating} || 'N/A';
232 my $author_id = $c->request->params->{author_id} || '1';
235 my $book = $c->model('MyAppDB::Book')->create({
239 # Handle relationship with author
240 $book->add_to_book_authors({author_id => $author_id});
242 # Store new model object in stash
243 $c->stash->{book} = $book;
245 # Avoid Data::Dumper issue mention earlier
246 # You can probably omit this
247 $Data::Dumper::Useperl = 1;
249 # Set the TT template to use
250 $c->stash->{template} = 'books/create_done.tt2';
254 =head2 Test Out The Form
256 If the application is still running from before, use C<Ctrl-C> to kill it. Then restart the server:
258 $ script/myapp_server.pl
260 Point your browser to L<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 C<create_done.tt2> template seen in earlier examples. Finally, click "Return to list" to view the full list of books.
262 B<Note:> Having the user enter the primary key ID for the author is obviously a bit crude; we will address this concern with a drop-down list in Part 8.
266 =head1 A SIMPLE DELETE FEATURE
268 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.
271 =head2 Include a Delete Link in the List
273 Edit C<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).
275 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
276 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
277 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
278 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
280 [% # Provide a title to root/lib/site/header -%]
281 [% META title = 'Book List' -%]
284 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
285 [% # Display each book in a table row %]
286 [% FOREACH book IN books -%]
288 <td>[% book.title %]</td>
289 <td>[% book.rating %]</td>
291 [% # Print author count in parens. 'book.authors' uses the 'many_to_many' -%]
292 [% # relationship to retrieve all of the authors of a book. 'size' is a -%]
293 [% # TT VMethod to get the number of elements in a list. -%]
294 ([% book.authors.size %])
295 [% # Use an alternate form of a FOREACH loop to display authors. -%]
296 [% # _ below is the TT string concatenation operator. -%]
297 [% author.last_name _' ' FOREACH author = book.authors %]
298 [% # Note: if many_to_many relationship not used in Authors.pm, you could -%]
299 [% # have used the following to 'walk' through the 'join table objects' -%]
300 [% # bk_author.author.last_name _' ' FOREACH bk_author = book.book_authors %]
303 [% # Add a link to delete a book %]
304 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
310 The additional code is obviously designed to add a new column to the right side of the table with a C<Delete> "button" (for simplicity, links will be used instead of full HTML buttons).
313 =head2 Add a Delete Action to the Controller
315 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the following method:
324 # $id = primary key of book to delete
325 my ($self, $c, $id) = @_;
327 # Search for the book and then delete it
328 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
330 # Set a status message to be displayed at the top of the view
331 $c->stash->{status_msg} = "Book deleted.";
333 # Forward to the list action/method in this controller
337 This method first deletes the book with the specified primary key ID. However, it also removes the corresponding entry from the C<book_authors> table. Note that C<delete_all> was used instead of C<delete>: whereas C<delete_all> also removes the join table entries in C<book_authors>, C<delete> does not.
339 Then, rather than forwarding to a "delete done" page as we did with the earlier create example, it simply sets the C<status_msg> to display a notification to the user as the normal list view is rendered.
341 The C<delete> action uses the context C<forward> method to return the user to the book list. The C<detach> method could have also been used. Whereas C<forward> I<returns> to the original action once it is completed, C<detach> does I<not> return. Other than that, the two are equivalent.
343 Another alternative to C<forward> would be to use C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The C<forward> and C<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.
346 =head2 Try the Delete Feature
348 If the application is still running from before, use C<Ctrl-C> to kill it. Then restart the server:
350 $ script/myapp_server.pl
352 Then point your browser to L<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.
358 Kennedy Clark, C<hkclark@gmail.com>
360 Please report any errors, issues or suggestions to the author.
362 Copyright 2006, Kennedy Clark. All rights reserved.
364 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.