Apply manual patch from Del Merritt
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / BasicCRUD.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 4: Basic CRUD
4
5
6 =head1 OVERVIEW
7
8 This is B<Part 4 of 10> for the Catalyst tutorial.
9
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12 =over 4
13
14 =item 1
15
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18 =item 2
19
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22 =item 3
23
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
25
26 =item 4
27
28 B<Basic CRUD>
29
30 =item 5
31
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33
34 =item 6
35
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37
38 =item 7
39
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41
42 =item 8
43
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
45
46 =item 9
47
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49
50 =item 10
51
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
53
54 =back
55
56
57 =head1 DESCRIPTION
58
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
67 Part 9.
68
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>.
76
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>.
80
81
82 =head1 FORMLESS SUBMISSION
83
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).
87
88
89 =head2 Include a Create Action in the Books Controller
90
91 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
92
93     =head2 url_create
94     
95     Create a book with the supplied title, rating, and author
96     
97     =cut
98     
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/" 
103         # into @_
104         my ($self, $c, $title, $rating, $author_id) = @_;
105     
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({
109                 title  => $title,
110                 rating => $rating
111             });
112         
113         # Add a record to the join table for this book, mapping to 
114         # appropriate author
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});
118         
119         # Assign the Book object to the stash for display in the view
120         $c->stash->{book} = $book;
121     
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;
129     
130         # Set the TT template to use
131         $c->stash->{template} = 'books/create_done.tt2';
132     }
133
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.
141
142
143 =head2 Include a Template for the C<url_create> Action:
144
145 Edit C<root/src/books/create_done.tt2> and then enter:
146
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) -%]
151     
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' %]
157     
158     [% # Output information about the record that was added.  First title.       -%]
159     <p>Added book '[% book.title %]'
160     
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 %]'
169     
170     [% # Output the rating for the book that was added -%]
171     with a rating of [% book.rating %].</p>
172     
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>
176     
177     [% # Try out the TT Dumper (for development only!) -%]
178     <pre>
179     Dump of the 'book' variable:
180     [% Dumper.dump(book) %]
181     </pre>
182
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.
189
190
191 =head2 Try the C<url_create> Feature
192
193 If the application is still running from before, use C<Ctrl-C> to kill
194 it. Then restart the server:
195
196     $ DBIC_TRACE=1 script/myapp_server.pl
197
198 Note that new path for C</books/url_create> appears in the startup debug
199 output.
200
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).
207
208 Next, use your browser to enter the following URL:
209
210     http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
211
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:
216
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'
222
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)>.
226
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).
230
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
234 URL):
235
236     http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
237
238 You should be able to click "Return to list" and now see 3 copies of 
239 "TCP_Illustrated_Vol-2".
240
241
242 =head1 MANUALLY BUILDING A CREATE FORM
243
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.
248
249
250 =head2 Add Method to Display The Form
251
252 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
253
254     =head2 form_create
255     
256     Display form to collect information for book to create
257     
258     =cut
259     
260     sub form_create : Local {
261         my ($self, $c) = @_;
262     
263         # Set the TT template to use
264         $c->stash->{template} = 'books/form_create.tt2';
265     }
266
267 This action simply invokes a view containing a book creation form.
268
269
270 =head2 Add a Template for the Form
271
272 Open C<root/src/books/form_create.tt2> in your editor and enter:
273
274     [% META title = 'Manual Form Book Create' -%]
275     
276     <form method="post" action="[% c.uri_for('form_create_do') %]">
277     <table>
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>
281     </table>
282     <input type="submit" name="Submit" value="Submit">
283     </form>
284
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.
287
288
289 =head2 Add a Method to Process Form Values and Update Database
290
291 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
292 save the form information to the database:
293
294     =head2 form_create_do
295     
296     Take information from form and add to database
297     
298     =cut
299     
300     sub form_create_do : Local {
301         my ($self, $c) = @_;
302     
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';
307     
308         # Create the book
309         my $book = $c->model('DB::Books')->create({
310                 title   => $title,
311                 rating  => $rating,
312             });
313         # Handle relationship with author
314         $book->add_to_book_authors({author_id => $author_id});
315     
316         # Store new model object in stash
317         $c->stash->{book} = $book;
318     
319         # Avoid Data::Dumper issue mentioned earlier
320         # You can probably omit this    
321         $Data::Dumper::Useperl = 1;
322     
323         # Set the TT template to use
324         $c->stash->{template} = 'books/create_done.tt2';
325     }
326
327
328 =head2 Test Out The Form
329
330 If the application is still running from before, use C<Ctrl-C> to kill
331 it.  Then restart the server:
332
333     $ script/myapp_server.pl
334
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.
340
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
343 Part 9.
344
345
346 =head1 A SIMPLE DELETE FEATURE
347
348 Turning our attention to the delete portion of CRUD, this section
349 illustrates some basic techniques that can be used to remove information
350 from the database.
351
352
353 =head2 Include a Delete Link in the List
354
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).
358
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. -%]
363     
364     [% # Provide a title to root/lib/site/header -%]
365     [% META title = 'Book List' -%]
366     
367     <table>
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 -%]
371       <tr>
372         <td>[% book.title %]</td>
373         <td>[% book.rating %]</td>
374         <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.                                 -%]
382           [% tt_authors = [ ];
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(', ') %]
388         </td>
389         <td>
390           [% # Add a link to delete a book %]
391           <a href="[% c.uri_for('delete', book.id) %]">Delete</a>
392         </td>
393       </tr>
394     [% END -%]
395     </table>
396
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, 
399 links will be used instead of full HTML buttons).
400
401 B<Note:> You should use more than just a simple link with your 
402 applications. Consider using some sort of of confirmation page 
403 (typically with unique actions in your controller for both the 
404 confirmation and the actual delete operation).  Also, you should try 
405 to use an HTTP POST operation (versus the GET used here) for 
406 operations that change the state of your application (e.g., the 
407 database).
408
409
410 =head2 Add a Delete Action to the Controller
411
412 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
413 following method:
414
415     =head2 delete
416     
417     Delete a book
418         
419     =cut
420     
421     sub delete : Local {
422         # $id = primary key of book to delete
423         my ($self, $c, $id) = @_;
424     
425         # Search for the book and then delete it
426         $c->model('DB::Books')->search({id => $id})->delete_all;
427     
428         # Set a status message to be displayed at the top of the view
429         $c->stash->{status_msg} = "Book deleted.";
430     
431         # Forward to the list action/method in this controller
432         $c->forward('list');
433     }
434
435 This method first deletes the book with the specified primary key ID.
436 However, it also removes the corresponding entry from the
437 C<book_authors> table.  Note that C<delete_all> was used instead of
438 C<delete>: whereas C<delete_all> also removes the join table entries in
439 C<book_authors>, C<delete> does not (only use C<delete_all> if you
440 really need the cascading deletes... otherwise you are wasting resources).
441
442 Then, rather than forwarding to a "delete done" page as we did with the
443 earlier create example, it simply sets the C<status_msg> to display a
444 notification to the user as the normal list view is rendered.
445
446 The C<delete> action uses the context C<forward> method to return the
447 user to the book list.  The C<detach> method could have also been used.
448 Whereas C<forward> I<returns> to the original action once it is
449 completed, C<detach> does I<not> return.  Other than that, the two are
450 equivalent.
451
452
453 =head2 Try the Delete Feature
454
455 If the application is still running from before, use C<Ctrl-C> to kill
456 it.  Then restart the server:
457
458     $ script/myapp_server.pl
459
460 Then point your browser to L<http://localhost:3000/books/list> and click
461 the "Delete" link next to the first "TCPIP_Illustrated_Vol-2".  A green 
462 "Book deleted" status message should display at the top of the page, 
463 along with a list of the eight remaining books.
464
465
466 =head2 Fixing a Dangerous URL
467
468 Note the URL in your browser once you have performed the deletion in the 
469 prior step -- it is still referencing the delete action:
470
471     http://localhost:3000/books/delete/6
472
473 What if the user were to press reload with this URL still active?  In
474 this case the redundant delete is harmless, but in other cases this
475 could clearly be extremely dangerous.
476
477 We can improve the logic by converting to a redirect.  Unlike
478 C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
479 a server-side alteration in the flow of processing, a redirect is a
480 client-side mechanism that causes the browser to issue an entirely
481 new request.  As a result, the URL in the browser is updated to match
482 the destination of the redirection URL.
483
484 To convert the forward used in the previous section to a redirect,
485 open C<lib/MyApp/Controller/Books.pm> and edit the existing 
486 C<sub delete> method to match:
487
488     =head2 delete 
489     
490     Delete a book
491         
492     =cut
493     
494     sub delete : Local {
495         # $id = primary key of book to delete
496         my ($self, $c, $id) = @_;
497     
498         # Search for the book and then delete it
499         $c->model('DB::Books')->search({id => $id})->delete_all;
500     
501         # Set a status message to be displayed at the top of the view
502         $c->stash->{status_msg} = "Book deleted.";
503     
504         # Redirect the user back to the list page
505         $c->response->redirect($c->uri_for('/books/list'));
506     }
507
508
509 =head2 Try the Delete and Redirect Logic
510
511 Restart the development server and point your browser to 
512 L<http://localhost:3000/books/list> and delete the first copy of 
513 "TCPIP_Illustrated_Vol-2".  The URL in your browser should return to 
514 the L<http://localhost:3000/books/list> URL, so that is an 
515 improvement, but notice that I<no green "Book deleted" status message 
516 is displayed>.  Because the stash is reset on every request (and a 
517 redirect involves a second request), the C<status_msg> is cleared 
518 before it can be displayed.
519
520
521 =head2 Using C<uri_for> to Pass Query Parameters
522
523 There are several ways to pass information across a redirect. 
524 In general, the best option is to use the C<flash> technique that we
525 will see in Part 5 of the tutorial; however, here we will pass the
526 information via query parameters on the redirect itself.  Open 
527 C<lib/MyApp/Controller/Books.pm> and update the existing 
528 C<sub delete> method to match the following:
529
530     =head2 delete 
531     
532     Delete a book
533         
534     =cut
535     
536     sub delete : Local {
537         # $id = primary key of book to delete
538         my ($self, $c, $id) = @_;
539     
540         # Search for the book and then delete it
541         $c->model('DB::Books')->search({id => $id})->delete_all;
542     
543         # Redirect the user back to the list page with status msg as an arg
544         $c->response->redirect($c->uri_for('/books/list', 
545             {status_msg => "Book deleted."}));
546     }
547
548 This modification simply leverages the ability of C<uri_for> to include
549 an arbitrary number of name/value pairs in a hash reference.  Next, we 
550 need to update C<root/src/wrapper> to handle C<status_msg> as a 
551 query parameter:
552
553     ...
554     <div id="content">
555         [%# Status and error messages %]
556         <span class="message">[% status_msg || c.request.params.status_msg %]</span>
557         <span class="error">[% error_msg %]</span>
558         [%# This is where TT will stick all of your template's contents. -%]
559         [% content %]
560     </div><!-- end content -->
561     ...
562
563 Although the sample above only shows the C<content> div, leave the 
564 rest of the file intact -- the only change we made to the C<wrapper.tt2>
565 was to add "C<|| c.request.params.status_msg>" to the 
566 C<E<lt>span class="message"E<gt>> line.
567
568
569 =head2 Try the Delete and Redirect With Query Param Logic
570
571 Restart the development server and point your browser to 
572 L<http://localhost:3000/books/list>.  Then delete the remaining copy 
573 of "TCPIP_Illustrated_Vol-2".  The green "Book deleted" status message
574 should return.
575
576 B<NOTE:> Although this did present an opportunity to show a handy
577 capability of C<uri_for>, it would be much better to use Catalyst's
578 C<flash> feature in this situation.  Although the technique here is 
579 less dangerous than leaving the delete URL in the client's browser, 
580 we have still exposed the status message to the user.  With C<flash>, 
581 this message returns to its rightful place as a service-side 
582 mechanism (we will migrate this code to C<flash> in the next part 
583 of the tutorial).
584
585
586 =head1 AUTHOR
587
588 Kennedy Clark, C<hkclark@gmail.com>
589
590 Please report any errors, issues or suggestions to the author.  The
591 most recent version of the Catalyst Tutorial can be found at
592 L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
593
594 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
595 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).
596