3 Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 4: Basic CRUD
8 This is B<Part 4 of 10> 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>
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
59 This part of the tutorial builds on the fairly primitive application
60 created in Part 3 to add basic support for Create, Read, Update, and
61 Delete (CRUD) of C<Book> objects. Note that the 'list' function in Part
62 2 already implements the Read portion of CRUD (although Read normally
63 refers to reading a single object; you could implement full read
64 functionality using the techniques introduced below). This section will
65 focus on the Create and Delete aspects of CRUD. More advanced
66 capabilities, including full Update functionality, will be addressed in
69 Although this part of the tutorial will show you how to build CRUD
70 functionality yourself, another option is to use a "CRUD builder" type
71 of tool to automate the process. You get less control, but it's quick
72 and easy. For example, see
73 L<CatalystX::ListFramework::Builder|CatalystX::ListFramework::Builder>,
74 L<CatalystX::CRUD|CatalystX::CRUD>, and
75 L<CatalystX::CRUD:YUI|CatalystX::CRUD:YUI>.
77 You can checkout the source code for this example from the catalyst
78 subversion repository as per the instructions in
79 L<Catalyst::Manual::Tutorial::Intro|Catalyst::Manual::Tutorial::Intro>.
82 =head1 FORMLESS SUBMISSION
84 Our initial attempt at object creation will utilize the "URL
85 arguments" feature of Catalyst (we will employ the more common form-
86 based submission in the sections that follow).
89 =head2 Include a Create Action in the Books Controller
91 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
95 Create a book with the supplied title, rating, and author
99 sub url_create : Local {
100 # In addition to self & context, get the title, rating, &
101 # author_id args from the URL. Note that Catalyst automatically
102 # puts extra information after the "/<controller_name>/<action_name/"
104 my ($self, $c, $title, $rating, $author_id) = @_;
106 # Call create() on the book model object. Pass the table
107 # columns/field values we want to set as hash values
108 my $book = $c->model('DB::Books')->create({
113 # Add a record to the join table for this book, mapping to
115 $book->add_to_book_authors({author_id => $author_id});
116 # Note: Above is a shortcut for this:
117 # $book->create_related('book_authors', {author_id => $author_id});
119 # Assign the Book object to the stash for display in the view
120 $c->stash->{book} = $book;
122 # This is a hack to disable XSUB processing in Data::Dumper
123 # (it's used in the view). This is a work-around for a bug in
124 # the interaction of some versions or Perl, Data::Dumper & DBIC.
125 # You won't need this if you aren't using Data::Dumper (or if
126 # you are running DBIC 0.06001 or greater), but adding it doesn't
127 # hurt anything either.
128 $Data::Dumper::Useperl = 1;
130 # Set the TT template to use
131 $c->stash->{template} = 'books/create_done.tt2';
134 Notice that Catalyst takes "extra slash-separated information" from the
135 URL and passes it as arguments in C<@_>. The C<url_create> action then
136 uses a simple call to the DBIC C<create> method to add the requested
137 information to the database (with a separate call to
138 C<add_to_book_authors> to update the join table). As do virtually all
139 controller methods (at least the ones that directly handle user input),
140 it then sets the template that should handle this request.
143 =head2 Include a Template for the C<url_create> Action:
145 Edit C<root/src/books/create_done.tt2> and then enter:
147 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
148 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
149 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
150 [% USE Dumper(Indent=1) -%]
152 [% # Set the page title. META can 'go back' and set values in templates -%]
153 [% # that have been processed 'before' this template (here it's for -%]
154 [% # root/lib/site/html and root/lib/site/header). Note that META on -%]
155 [% # simple strings (e.g., no variable interpolation). -%]
156 [% META title = 'Book Created' %]
158 [% # Output information about the record that was added. First title. -%]
159 <p>Added book '[% book.title %]'
161 [% # Output the last name of the first author. This is complicated by an -%]
162 [% # issue in TT 2.15 where blessed hash objects are not handled right. -%]
163 [% # First, fetch 'book.authors' from the DB once. -%]
164 [% authors = book.authors %]
165 [% # Now use IF statements to test if 'authors.first' is "working". If so, -%]
166 [% # we use it. Otherwise we use a hack that seems to keep TT 2.15 happy. -%]
167 by '[% authors.first.last_name IF authors.first;
168 authors.list.first.value.last_name IF ! authors.first %]'
170 [% # Output the rating for the book that was added -%]
171 with a rating of [% book.rating %].</p>
173 [% # Provide a link back to the list page -%]
174 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
175 <p><a href="[% c.uri_for('/books/list') %]">Return to list</a></p>
177 [% # Try out the TT Dumper (for development only!) -%]
179 Dump of the 'book' variable:
180 [% Dumper.dump(book) %]
183 The TT C<USE> directive allows access to a variety of plugin modules
184 (TT plugins, that is, not Catalyst plugins) to add extra functionality
185 to the base TT capabilities. Here, the plugin allows
186 L<Data::Dumper|Data::Dumper> "pretty printing" of objects and
187 variables. Other than that, the rest of the code should be familiar
188 from the examples in Part 3.
191 =head2 Try the C<url_create> Feature
193 If the application is still running from before, use C<Ctrl-C> to kill
194 it. Then restart the server:
196 $ DBIC_TRACE=1 script/myapp_server.pl
198 Note that new path for C</books/url_create> appears in the startup debug
201 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
202 server auto-detect changed files and reload itself (if your browser acts
203 odd, you should also try throwing in a C<-k>). If you make changes to
204 the TT templates only, you do not need to reload the development server
205 (only changes to "compiled code" such as Controller and Model C<.pm>
206 files require a reload).
208 Next, use your browser to enter the following URL:
210 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
212 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by
213 'Stevens' with a rating of 5." along with a dump of the new book model
214 object. You should also see the following DBIC debug messages displayed
215 in the development server log messages if you have DBIC_TRACE set:
217 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
218 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
219 SELECT author.id, author.first_name, author.last_name
220 FROM book_authors me JOIN authors author
221 ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '6'
223 The C<INSERT> statements are obviously adding the book and linking it to
224 the existing record for Richard Stevens. The C<SELECT> statement results
225 from DBIC automatically fetching the book for the C<Dumper.dump(book)>.
227 If you then click the "Return to list" link, you should find that
228 there are now six books shown (if necessary, Shift+Reload or
229 Ctrl+Reload your browser at the C</books/list> page).
231 Then I<add 2 more copies of the same book> so that we have some extras for
232 our delete logic that will be coming up soon. Enter the same URL above
233 two more times (or refresh your browser twice if it still contains this
236 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
238 You should be able to click "Return to list" and now see 3 copies of
239 "TCP_Illustrated_Vol-2".
242 =head1 MANUALLY BUILDING A CREATE FORM
244 Although the C<url_create> action in the previous step does begin to
245 reveal the power and flexibility of both Catalyst and DBIC, it's
246 obviously not a very realistic example of how users should be expected
247 to enter data. This section begins to address that concern.
250 =head2 Add Method to Display The Form
252 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
256 Display form to collect information for book to create
260 sub form_create : Local {
263 # Set the TT template to use
264 $c->stash->{template} = 'books/form_create.tt2';
267 This action simply invokes a view containing a book creation form.
270 =head2 Add a Template for the Form
272 Open C<root/src/books/form_create.tt2> in your editor and enter:
274 [% META title = 'Manual Form Book Create' -%]
276 <form method="post" action="[% c.uri_for('form_create_do') %]">
278 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
279 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
280 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
282 <input type="submit" name="Submit" value="Submit">
285 Note that we have specified the target of the form data as
286 C<form_create_do>, the method created in the section that follows.
289 =head2 Add a Method to Process Form Values and Update Database
291 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
292 save the form information to the database:
294 =head2 form_create_do
296 Take information from form and add to database
300 sub form_create_do : Local {
303 # Retrieve the values from the form
304 my $title = $c->request->params->{title} || 'N/A';
305 my $rating = $c->request->params->{rating} || 'N/A';
306 my $author_id = $c->request->params->{author_id} || '1';
309 my $book = $c->model('DB::Books')->create({
313 # Handle relationship with author
314 $book->add_to_book_authors({author_id => $author_id});
316 # Store new model object in stash
317 $c->stash->{book} = $book;
319 # Avoid Data::Dumper issue mentioned earlier
320 # You can probably omit this
321 $Data::Dumper::Useperl = 1;
323 # Set the TT template to use
324 $c->stash->{template} = 'books/create_done.tt2';
328 =head2 Test Out The Form
330 If the application is still running from before, use C<Ctrl-C> to kill
331 it. Then restart the server:
333 $ script/myapp_server.pl
335 Point your browser to L<http://localhost:3000/books/form_create> and
336 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
337 author ID of 4. You should then see the output of the same
338 C<create_done.tt2> template seen in earlier examples. Finally, click
339 "Return to list" to view the full list of books.
341 B<Note:> Having the user enter the primary key ID for the author is
342 obviously crude; we will address this concern with a drop-down list in
346 =head1 A SIMPLE DELETE FEATURE
348 Turning our attention to the delete portion of CRUD, this section
349 illustrates some basic techniques that can be used to remove information
353 =head2 Include a Delete Link in the List
355 Edit C<root/src/books/list.tt2> and update it to the following (two
356 sections have changed: 1) the additional '<th>Links</th>' table header,
357 and 2) the four lines for the Delete link near the bottom).
359 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
360 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
361 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
362 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
364 [% # Provide a title to root/lib/site/header -%]
365 [% META title = 'Book List' -%]
368 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
369 [% # Display each book in a table row %]
370 [% FOREACH book IN books -%]
372 <td>[% book.title %]</td>
373 <td>[% book.rating %]</td>
375 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
376 [% # loop in 'side effect notation' to load just the last names of the -%]
377 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
378 [% # a value, so nothing will be printed here. But, if you have something -%]
379 [% # in TT that does return a method and you don't want it printed, you -%]
380 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
381 [% # call it and discard the return value. -%]
383 tt_authors.push(author.last_name) FOREACH author = book.authors %]
384 [% # Now use a TT 'virtual method' to display the author count in parens -%]
385 ([% tt_authors.size %])
386 [% # Use another TT vmethod to join & print the names & comma separators -%]
387 [% tt_authors.join(', ') %]
390 [% # Add a link to delete a book %]
391 <a href="[% c.uri_for('delete', book.id) %]">Delete</a>
397 The additional code is obviously designed to add a new column to the
398 right side of the table with a C<Delete> "button" (for simplicity, links
399 will be used instead of full HTML buttons).
402 =head2 Add a Delete Action to the Controller
404 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
414 # $id = primary key of book to delete
415 my ($self, $c, $id) = @_;
417 # Search for the book and then delete it
418 $c->model('DB::Books')->search({id => $id})->delete_all;
420 # Set a status message to be displayed at the top of the view
421 $c->stash->{status_msg} = "Book deleted.";
423 # Forward to the list action/method in this controller
427 This method first deletes the book with the specified primary key ID.
428 However, it also removes the corresponding entry from the
429 C<book_authors> table. Note that C<delete_all> was used instead of
430 C<delete>: whereas C<delete_all> also removes the join table entries in
431 C<book_authors>, C<delete> does not (only use C<delete_all> if you
432 really need the cascading deletes... otherwise you are wasting resources).
434 Then, rather than forwarding to a "delete done" page as we did with the
435 earlier create example, it simply sets the C<status_msg> to display a
436 notification to the user as the normal list view is rendered.
438 The C<delete> action uses the context C<forward> method to return the
439 user to the book list. The C<detach> method could have also been used.
440 Whereas C<forward> I<returns> to the original action once it is
441 completed, C<detach> does I<not> return. Other than that, the two are
445 =head2 Try the Delete Feature
447 If the application is still running from before, use C<Ctrl-C> to kill
448 it. Then restart the server:
450 $ script/myapp_server.pl
452 Then point your browser to L<http://localhost:3000/books/list> and click
453 the "Delete" link next to the first "TCPIP_Illustrated_Vol-2". A green
454 "Book deleted" status message should display at the top of the page,
455 along with a list of the eight remaining books.
458 =head2 Fixing a Dangerous URL
460 Note the URL in your browser once you have performed the deletion in the
461 prior step -- it is still referencing the delete action:
463 http://localhost:3000/books/delete/6
465 What if the user were to press reload with this URL still active? In
466 this case the redundant delete is harmless, but in other cases this
467 could clearly be extremely dangerous.
469 We can improve the logic by converting to a redirect. Unlike
470 C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
471 a server-side alteration in the flow of processing, a redirect is a
472 client-side mechanism that causes the browser to issue an entirely
473 new request. As a result, the URL in the browser is updated to match
474 the destination of the redirection URL.
476 To convert the forward used in the previous section to a redirect,
477 open C<lib/MyApp/Controller/Books.pm> and edit the existing
478 C<sub delete> method to match:
487 # $id = primary key of book to delete
488 my ($self, $c, $id) = @_;
490 # Search for the book and then delete it
491 $c->model('DB::Books')->search({id => $id})->delete_all;
493 # Set a status message to be displayed at the top of the view
494 $c->stash->{status_msg} = "Book deleted.";
496 # Redirect the user back to the list page
497 $c->response->redirect($c->uri_for('/books/list'));
501 =head2 Try the Delete and Redirect Logic
503 Restart the development server and point your browser to
504 L<http://localhost:3000/books/list> and delete the first copy of
505 "TCPIP_Illustrated_Vol-2". The URL in your browser should return to
506 the L<http://localhost:3000/books/list> URL, so that is an
507 improvement, but notice that I<no green "Book deleted" status message
508 is displayed>. Because the stash is reset on every request (and a
509 redirect involves a second request), the C<status_msg> is cleared
510 before it can be displayed.
513 =head2 Using C<uri_for> to Pass Query Parameters
515 There are several ways to pass information across a redirect.
516 In general, the best option is to use the C<flash> technique that we
517 will see in Part 5 of the tutorial; however, here we will pass the
518 information via query parameters on the redirect itself. Open
519 C<lib/MyApp/Controller/Books.pm> and update the existing
520 C<sub delete> method to match the following:
529 # $id = primary key of book to delete
530 my ($self, $c, $id) = @_;
532 # Search for the book and then delete it
533 $c->model('DB::Books')->search({id => $id})->delete_all;
535 # Redirect the user back to the list page with status msg as an arg
536 $c->response->redirect($c->uri_for('/books/list',
537 {status_msg => "Book deleted."}));
540 This modification simply leverages the ability of C<uri_for> to include
541 an arbitrary number of name/value pairs in a hash reference. Next, we
542 need to update C<root/src/wrapper> to handle C<status_msg> as a
547 [%# Status and error messages %]
548 <span class="message">[% status_msg || c.request.params.status_msg %]</span>
549 <span class="error">[% error_msg %]</span>
550 [%# This is where TT will stick all of your template's contents. -%]
552 </div><!-- end content -->
555 Although the sample above only shows the C<content> div, leave the
556 rest of the file intact -- the only change we made to the C<wrapper.tt2>
557 was to add "C<|| c.request.params.status_msg>" to the
558 C<E<lt>span class="message"E<gt>> line.
561 =head2 Try the Delete and Redirect With Query Param Logic
563 Restart the development server and point your browser to
564 L<http://localhost:3000/books/list>. Then delete the remaining copy
565 of "TCPIP_Illustrated_Vol-2". The green "Book deleted" status message
568 B<NOTE:> Although this did present an opportunity to show a handy
569 capability of C<uri_for>, it would be much better to use Catalyst's
570 C<flash> feature in this situation. Although the technique here is
571 less dangerous than leaving the delete URL in the client's browser,
572 we have still exposed the status message to the user. With C<flash>,
573 this message returns to its rightful place as a service-side
574 mechanism (we will migrate this code to C<flash> in the next part
580 Kennedy Clark, C<hkclark@gmail.com>
582 Please report any errors, issues or suggestions to the author. The
583 most recent version of the Catalyst Tutorial can be found at
584 L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
586 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
587 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).