Fix Bug #42034
[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, links
399 will be used instead of full HTML buttons).
400
401
402 =head2 Add a Delete Action to the Controller
403
404 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
405 following method:
406
407     =head2 delete
408     
409     Delete a book
410         
411     =cut
412     
413     sub delete : Local {
414         # $id = primary key of book to delete
415         my ($self, $c, $id) = @_;
416     
417         # Search for the book and then delete it
418         $c->model('DB::Books')->search({id => $id})->delete_all;
419     
420         # Set a status message to be displayed at the top of the view
421         $c->stash->{status_msg} = "Book deleted.";
422     
423         # Forward to the list action/method in this controller
424         $c->forward('list');
425     }
426
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).
433
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.
437
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
442 equivalent.
443
444
445 =head2 Try the Delete Feature
446
447 If the application is still running from before, use C<Ctrl-C> to kill
448 it.  Then restart the server:
449
450     $ script/myapp_server.pl
451
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.
456
457
458 =head2 Fixing a Dangerous URL
459
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:
462
463     http://localhost:3000/books/delete/6
464
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.
468
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.
475
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:
479
480     =head2 delete 
481     
482     Delete a book
483         
484     =cut
485     
486     sub delete : Local {
487         # $id = primary key of book to delete
488         my ($self, $c, $id) = @_;
489     
490         # Search for the book and then delete it
491         $c->model('DB::Books')->search({id => $id})->delete_all;
492     
493         # Set a status message to be displayed at the top of the view
494         $c->stash->{status_msg} = "Book deleted.";
495     
496         # Redirect the user back to the list page
497         $c->response->redirect($c->uri_for('/books/list'));
498     }
499
500
501 =head2 Try the Delete and Redirect Logic
502
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.
511
512
513 =head2 Using C<uri_for> to Pass Query Parameters
514
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:
521
522     =head2 delete 
523     
524     Delete a book
525         
526     =cut
527     
528     sub delete : Local {
529         # $id = primary key of book to delete
530         my ($self, $c, $id) = @_;
531     
532         # Search for the book and then delete it
533         $c->model('DB::Books')->search({id => $id})->delete_all;
534     
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."}));
538     }
539
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 
543 query parameter:
544
545     ...
546     <div id="content">
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. -%]
551         [% content %]
552     </div><!-- end content -->
553     ...
554
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.
559
560
561 =head2 Try the Delete and Redirect With Query Param Logic
562
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
566 should return.
567
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 
575 of the tutorial).
576
577
578 =head1 AUTHOR
579
580 Kennedy Clark, C<hkclark@gmail.com>
581
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/>.
585
586 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
587 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).
588