3 Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD
8 This is B<Part 3 of 9> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
28 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
32 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
36 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
40 L<Testing|Catalyst::Manual::Tutorial::Testing>
44 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
48 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
56 This part of the tutorial builds on the fairly primitive application
57 created in Part 2 to add basic support for Create, Read, Update, and
58 Delete (CRUD) of C<Book> objects. Note that the 'list' function in Part
59 2 already implements the Read portion of CRUD (although Read normally
60 refers to reading a single object; you could implement full read
61 functionality using the techniques introduced below). This section will
62 focus on the Create and Delete aspects of CRUD. More advanced
63 capabilities, including full Update functionality, will be addressed in
66 You can checkout the source code for this example from the catalyst
67 subversion repository as per the instructions in
68 L<Catalyst::Manual::Tutorial::Intro>
70 =head1 FORMLESS SUBMISSION
72 Our initial attempt at object creation will utilize the "URL arguments"
73 feature of Catalyst (we will employ the more common form-based
74 submission in the sections that follow).
77 =head2 Include a Create Action in the Books Controller
79 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
83 Create a book with the supplied title, rating, and author
87 sub url_create : Local {
88 # In addition to self & context, get the title, rating, &
89 # author_id args from the URL. Note that Catalyst automatically
90 # puts extra information after the "/<controller_name>/<action_name/"
92 my ($self, $c, $title, $rating, $author_id) = @_;
94 # Call create() on the book model object. Pass the table
95 # columns/field values we want to set as hash values
96 my $book = $c->model('MyAppDB::Book')->create({
101 # Add a record to the join table for this book, mapping to
103 $book->add_to_book_authors({author_id => $author_id});
104 # Note: Above is a shortcut for this:
105 # $book->create_related('book_authors', {author_id => $author_id});
107 # Assign the Book object to the stash for display in the view
108 $c->stash->{book} = $book;
110 # This is a hack to disable XSUB processing in Data::Dumper
111 # (it's used in the view). This is a work-around for a bug in
112 # the interaction of some versions or Perl, Data::Dumper & DBIC.
113 # You won't need this if you aren't using Data::Dumper (or if
114 # you are running DBIC 0.06001 or greater), but adding it doesn't
115 # hurt anything either.
116 $Data::Dumper::Useperl = 1;
118 # Set the TT template to use
119 $c->stash->{template} = 'books/create_done.tt2';
122 Notice that Catalyst takes "extra slash-separated information" from the
123 URL and passes it as arguments in C<@_>. The C<url_create> action then
124 uses a simple call to the DBIC C<create> method to add the requested
125 information to the database (with a separate call to
126 C<add_to_book_authors> to update the join table). As do virtually all
127 controller methods (at least the ones that directly handle user input),
128 it then sets the template that should handle this request.
131 =head2 Include a Template for the C<url_create> Action:
133 Edit C<root/src/books/create_done.tt2> and then enter:
135 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
136 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
137 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
138 [% USE Dumper(Indent=1) -%]
140 [% # Set the page title. META can 'go back' and set values in templates -%]
141 [% # that have been processed 'before' this template (here it's for -%]
142 [% # root/lib/site/html and root/lib/site/header). Note that META on -%]
143 [% # simple strings (e.g., no variable interpolation). -%]
144 [% META title = 'Book Created' %]
146 [% # Output information about the record that was added. First title. -%]
147 <p>Added book '[% book.title %]'
149 [% # Output the last name of the first author. This is complicated by an -%]
150 [% # issue in TT 2.15 where blessed hash objects are not handled right. -%]
151 [% # First, fetch 'book.authors' from the DB once. -%]
152 [% authors = book.authors %]
153 [% # Now use IF statements to test if 'authors.first' is "working". If so, -%]
154 [% # we use it. Otherwise we use a hack that seems to keep TT 2.15 happy. -%]
155 by '[% authors.first.last_name IF authors.first;
156 authors.list.first.value.last_name IF ! authors.first %]'
158 [% # Output the rating for the book that was added -%]
159 with a rating of [% book.rating %].</p>
161 [% # Provide a link back to the list page -%]
162 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
163 <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
165 [% # Try out the TT Dumper (for development only!) -%]
167 Dump of the 'book' variable:
168 [% Dumper.dump(book) %]
171 The TT C<USE> directive allows access to a variety of plugin modules (TT
172 plugins, that is, not Catalyst plugins) to add extra functionality to
173 the base TT capabilities. Here, the plugin allows L<Data::Dumper>
174 "pretty printing" of objects and variables. Other than that, the rest
175 of the code should be familiar from the examples in Part 2.
177 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
178 class created by TTSite redefines the name used to access the Catalyst
179 context object in TT templates from the usual C<c> to C<Catalyst>.
181 =head2 Try the C<url_create> Feature
183 If the application is still running from before, use C<Ctrl-C> to kill
184 it. Then restart the server:
186 $ script/myapp_server.pl
188 Note that new path for C</books/url_create> appears in the startup debug
191 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
192 server auto-detect changed files and reload itself (if your browser acts
193 odd, you should also try throwing in a C<-k>). If you make changes to
194 the TT templates only, you do not need to reload the development server
195 (only changes to "compiled code" such as Controller and Model C<.pm>
196 files require a reload).
198 Next, use your browser to enter the following URL:
200 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
202 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by
203 'Stevens' with a rating of 5." along with a dump of the new book model
204 object. You should also see the following DBIC debug messages displayed
205 in the development server log messages:
207 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
208 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
209 SELECT author.id, author.first_name, author.last_name
210 FROM book_authors me JOIN authors author
211 ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '6'
213 The C<INSERT> statements are obviously adding the book and linking it to
214 the existing record for Richard Stevens. The C<SELECT> statement results
215 from DBIC automatically fetching the book for the C<Dumper.dump(book)>.
217 If you then click the "Return to list" link, you should find that there
218 are now six books shown (if necessary, Shift-Reload your browser at the
219 C</books/list> page).
221 Then I<add 2 more copies of the same book> so that we have some extras for
222 our delete logic that will be coming up soon. Enter the same URL above
223 two more times (or refresh your browser twice if it still contains this
226 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
228 You should be able to click "Return to list" and now see 3 copies of
229 "TCP_Illustrated_Vol-2".
232 =head1 MANUALLY BUILDING A CREATE FORM
234 Although the C<url_create> action in the previous step does begin to
235 reveal the power and flexibility of both Catalyst and DBIC, it's
236 obviously not a very realistic example of how users should be expected
237 to enter data. This section begins to address that concern.
240 =head2 Add Method to Display The Form
242 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
246 Display form to collect information for book to create
250 sub form_create : Local {
253 # Set the TT template to use
254 $c->stash->{template} = 'books/form_create.tt2';
257 This action simply invokes a view containing a book creation form.
259 =head2 Add a Template for the Form
261 Open C<root/src/books/form_create.tt2> in your editor and enter:
263 [% META title = 'Manual Form Book Create' -%]
265 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
267 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
268 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
269 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
271 <input type="submit" name="Submit" value="Submit">
274 Note that we have specified the target of the form data as
275 C<form_create_do>, the method created in the section that follows.
277 =head2 Add a Method to Process Form Values and Update Database
279 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
280 save the form information to the database:
282 =head2 form_create_do
284 Take information from form and add to database
288 sub form_create_do : Local {
291 # Retrieve the values from the form
292 my $title = $c->request->params->{title} || 'N/A';
293 my $rating = $c->request->params->{rating} || 'N/A';
294 my $author_id = $c->request->params->{author_id} || '1';
297 my $book = $c->model('MyAppDB::Book')->create({
301 # Handle relationship with author
302 $book->add_to_book_authors({author_id => $author_id});
304 # Store new model object in stash
305 $c->stash->{book} = $book;
307 # Avoid Data::Dumper issue mentioned earlier
308 # You can probably omit this
309 $Data::Dumper::Useperl = 1;
311 # Set the TT template to use
312 $c->stash->{template} = 'books/create_done.tt2';
316 =head2 Test Out The Form
318 If the application is still running from before, use C<Ctrl-C> to kill
319 it. Then restart the server:
321 $ script/myapp_server.pl
323 Point your browser to L<http://localhost:3000/books/form_create> and
324 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
325 author ID of 4. You should then be forwarded to the same
326 C<create_done.tt2> template seen in earlier examples. Finally, click
327 "Return to list" to view the full list of books.
329 B<Note:> Having the user enter the primary key ID for the author is
330 obviously crude; we will address this concern with a drop-down list in
334 =head1 A SIMPLE DELETE FEATURE
336 Turning our attention to the delete portion of CRUD, this section
337 illustrates some basic techniques that can be used to remove information
341 =head2 Include a Delete Link in the List
343 Edit C<root/src/books/list.tt2> and update it to the following (two
344 sections have changed: 1) the additional '<th>Links</th>' table header,
345 and 2) the four lines for the Delete link near the bottom).
347 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
348 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
349 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
350 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
352 [% # Provide a title to root/lib/site/header -%]
353 [% META title = 'Book List' -%]
356 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
357 [% # Display each book in a table row %]
358 [% FOREACH book IN books -%]
360 <td>[% book.title %]</td>
361 <td>[% book.rating %]</td>
363 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
364 [% # loop in 'side effect notation' to load just the last names of the -%]
365 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
366 [% # a value, so nothing will be printed here. But, if you have something -%]
367 [% # in TT that does return a method and you don't want it printed, you -%]
368 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
369 [% # call it and discard the return value. -%]
371 tt_authors.push(author.last_name) FOREACH author = book.authors %]
372 [% # Now use a TT 'virtual method' to display the author count in parens -%]
373 ([% tt_authors.size %])
374 [% # Use another TT vmethod to join & print the names & comma separators -%]
375 [% tt_authors.join(', ') %]
378 [% # Add a link to delete a book %]
379 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
385 The additional code is obviously designed to add a new column to the
386 right side of the table with a C<Delete> "button" (for simplicity, links
387 will be used instead of full HTML buttons).
389 =head2 Add a Delete Action to the Controller
391 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
401 # $id = primary key of book to delete
402 my ($self, $c, $id) = @_;
404 # Search for the book and then delete it
405 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
407 # Set a status message to be displayed at the top of the view
408 $c->stash->{status_msg} = "Book deleted.";
410 # Forward to the list action/method in this controller
414 This method first deletes the book with the specified primary key ID.
415 However, it also removes the corresponding entry from the
416 C<book_authors> table. Note that C<delete_all> was used instead of
417 C<delete>: whereas C<delete_all> also removes the join table entries in
418 C<book_authors>, C<delete> does not (only use C<delete_all> if you
419 really need the cascading deletes... otherwise you are wasting resources).
421 Then, rather than forwarding to a "delete done" page as we did with the
422 earlier create example, it simply sets the C<status_msg> to display a
423 notification to the user as the normal list view is rendered.
425 The C<delete> action uses the context C<forward> method to return the
426 user to the book list. The C<detach> method could have also been used.
427 Whereas C<forward> I<returns> to the original action once it is
428 completed, C<detach> does I<not> return. Other than that, the two are
432 =head2 Try the Delete Feature
434 If the application is still running from before, use C<Ctrl-C> to kill
435 it. Then restart the server:
437 $ script/myapp_server.pl
439 Then point your browser to L<http://localhost:3000/books/list> and click
440 the "Delete" link next to the first "TCPIP_Illustrated_Vol-2". A green
441 "Book deleted" status message should display at the top of the page,
442 along with a list of the eight remaining books.
445 =head2 Fixing a Dangerous URL
447 Note the URL in your browser once you have performed the deletetion in the
448 prior step -- it is still referencing the delete action:
450 http://localhost:3000/books/delete/6
452 What if the user were to press reload with this URL still active? In
453 this case the redundant delete is harmless, but in other cases this
454 could clearly be extremely dangerous.
456 We can improve the logic by converting to a redirect. Unlike
457 C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
458 a server-side alteration in the flow of processing, a redirect is a
459 client-side mechanism that causes the brower to issue an entirely
460 new request. As a result, the URL in the browser is updated to match
461 the destination of the redirection URL.
463 To convert the forward used in the previous section to a redirect,
464 open C<lib/MyApp/Controller/Books.pm> and edit the existing
465 C<sub delete> method to match:
474 # $id = primary key of book to delete
475 my ($self, $c, $id) = @_;
477 # Search for the book and then delete it
478 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
480 # Set a status message to be displayed at the top of the view
481 $c->stash->{status_msg} = "Book deleted.";
483 # Redirect the user back to the list page
484 $c->response->redirect($c->uri_for('/books/list'));
488 =head2 Try the Delete and Redirect Logic
490 Restart the development server and point your browser to
491 L<http://localhost:3000/books/list>. Delete the first copy of
492 "TCPIP_Illustrated_Vol-2", but notice that I<no green "Book deleted"
493 status message is displayed>. Because the stash is reset on every
494 request (and a redirect involves a second request), the
495 C<status_msg> is cleared before it can be displayed.
498 =head2 Using C<uri_for> to Pass Query Parameters
500 There are several ways to pass information across a redirect.
501 In general, the best option is to use the C<flash> technique that we
502 will see in Part 4 of the tutorial; however, here we will pass the
503 information via query parameters on the redirect itself. Open
504 C<lib/MyApp/Controller/Books.pm> and update the existing
505 C<sub delete> method to match the following:
514 # $id = primary key of book to delete
515 my ($self, $c, $id) = @_;
517 # Search for the book and then delete it
518 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
520 # Redirect the user back to the list page with status msg as an arg
521 $c->response->redirect($c->uri_for('/books/list',
522 {status_msg => "Book deleted."}));
525 This modification simply leverages the ability of C<uri_for> to include
526 an arbitrary number of name/value pairs in a hash reference. Next, we
527 need to update C<root/lib/site/layout> to handle C<status_msg> as a
530 <div id="header">[% PROCESS site/header %]</div>
533 <span class="message">[% status_msg || Catalyst.request.params.status_msg %]</span>
534 <span class="error">[% error_msg %]</span>
538 <div id="footer">[% PROCESS site/footer %]</div>
541 =head2 Try the Delete and Redirect With Query Param Logic
543 Restart the development server and point your browser to
544 L<http://localhost:3000/books/list>. Then delete the remaining copy
545 of "TCPIP_Illustrated_Vol-2". The green "Book deleted" status message
548 B<NOTE:> Although this did present an opportunity to show a handy
549 capability of C<uri_for>, it would be much better to use Catalyst's
550 C<flash> feature in this situation. Although the technique here is
551 less dangerous than leaving the delete URL in the client's browser,
552 we have still exposed the status message to the user. With C<flash>,
553 this message returns to its rightful place as a service-side
554 mechanism (we will migrate this code to C<flash> in the next part
560 Kennedy Clark, C<hkclark@gmail.com>
562 Please report any errors, issues or suggestions to the author. The
563 most recent version of the Catalyst Tutorial can be found at
564 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
566 Copyright 2006, Kennedy Clark, under Creative Commons License
567 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).