prepared for 03
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / BasicCRUD.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD
4d583dd8 4
5
6=head1 OVERVIEW
7
8This is B<Part 3 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
24B<Basic CRUD>
25
26=item 4
27
28L<Authentication|Catalyst::Manual::Tutorial::Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
44L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
45
46=item 9
47
7d310f12 48L<Appendices|Catalyst::Manual::Tutorial::Appendices>
4d583dd8 49
50=back
51
52
53
54=head1 DESCRIPTION
55
64ccd8a8 56This part of the tutorial builds on the fairly primitive application
57created in Part 2 to add basic support for Create, Read, Update, and
58Delete (CRUD) of C<Book> objects. Note that the 'list' function in Part
71dedf57 592 already implements the Read portion of CRUD (although Read normally
64ccd8a8 60refers to reading a single object; you could implement full read
61functionality using the techniques introduced below). This section will
62focus on the Create and Delete aspects of CRUD. More advanced
63capabilities, including full Update functionality, will be addressed in
64Part 8.
4d583dd8 65
936a5dd5 66You can checkout the source code for this example from the catalyst
67subversion repository as per the instructions in
68L<Catalyst::Manual::Tutorial::Intro>
4d583dd8 69
4d583dd8 70=head1 FORMLESS SUBMISSION
71
64ccd8a8 72Our initial attempt at object creation will utilize the "URL arguments"
73feature of Catalyst (we will employ the more common form-based
74submission in the sections that follow).
4d583dd8 75
76
77=head2 Include a Create Action in the Books Controller
78
79Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
80
81 =head2 url_create
82
71dedf57 83 Create a book with the supplied title, rating, and author
4d583dd8 84
85 =cut
86
87 sub url_create : Local {
71dedf57 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/"
91 # into @_
4d583dd8 92 my ($self, $c, $title, $rating, $author_id) = @_;
93
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({
5c1f2a06 97 title => $title,
98 rating => $rating
4d583dd8 99 });
100
101 # Add a record to the join table for this book, mapping to
102 # appropriate author
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});
106
107 # Assign the Book object to the stash for display in the view
108 $c->stash->{book} = $book;
109
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;
117
118 # Set the TT template to use
119 $c->stash->{template} = 'books/create_done.tt2';
120 }
121
64ccd8a8 122Notice that Catalyst takes "extra slash-separated information" from the
123URL and passes it as arguments in C<@_>. The C<url_create> action then
124uses a simple call to the DBIC C<create> method to add the requested
125information to the database (with a separate call to
126C<add_to_book_authors> to update the join table). As do virtually all
127controller methods (at least the ones that directly handle user input),
128it then sets the template that should handle this request.
4d583dd8 129
130
131=head2 Include a Template for the C<url_create> Action:
132
133Edit C<root/src/books/create_done.tt2> and then enter:
134
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) -%]
139
5c1f2a06 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). -%]
4d583dd8 144 [% META title = 'Book Created' %]
145
7d310f12 146 [% # Output information about the record that was added. First title. -%]
147 <p>Added book '[% book.title %]'
148
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 %]'
157
158 [% # Output the rating for the book that was added -%]
4d583dd8 159 with a rating of [% book.rating %].</p>
160
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>
164
71dedf57 165 [% # Try out the TT Dumper (for development only!) -%]
4d583dd8 166 <pre>
167 Dump of the 'book' variable:
168 [% Dumper.dump(book) %]
169 </pre>
170
71dedf57 171The TT C<USE> directive allows access to a variety of plugin modules (TT
172plugins, that is, not Catalyst plugins) to add extra functionality to
173the base TT capabilities. Here, the plugin allows L<Data::Dumper>
174"pretty printing" of objects and variables. Other than that, the rest
175of the code should be familiar from the examples in Part 2.
4d583dd8 176
64ccd8a8 177B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
178class created by TTSite redefines the name used to access the Catalyst
179context object in TT templates from the usual C<c> to C<Catalyst>.
4d583dd8 180
4d583dd8 181=head2 Try the C<url_create> Feature
182
64ccd8a8 183If the application is still running from before, use C<Ctrl-C> to kill
71dedf57 184it. Then restart the server:
4d583dd8 185
186 $ script/myapp_server.pl
187
64ccd8a8 188Note that new path for C</books/url_create> appears in the startup debug
189output.
4d583dd8 190
64ccd8a8 191B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
192server auto-detect changed files and reload itself (if your browser acts
193odd, you should also try throwing in a C<-k>). If you make changes to
71dedf57 194the TT templates only, you do not need to reload the development server
64ccd8a8 195(only changes to "compiled code" such as Controller and Model C<.pm>
196files require a reload).
4d583dd8 197
198Next, use your browser to enter the following URL:
199
200 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
201
64ccd8a8 202Your 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
204object. You should also see the following DBIC debug messages displayed
205in the development server log messages:
4d583dd8 206
207 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
208 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
f2c10d65 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'
212
213The C<INSERT> statements are obviously adding the book and linking it to
214the existing record for Richard Stevens. The C<SELECT> statement results
215from DBIC automatically fetching the book for the C<Dumper.dump(book)>.
4d583dd8 216
64ccd8a8 217If you then click the "Return to list" link, you should find that there
218are now six books shown (if necessary, Shift-Reload your browser at the
219C</books/list> page).
4d583dd8 220
f2c10d65 221Then I<add 2 more copies of the same book> so that we have some extras for
222our delete logic that will be coming up soon. Enter the same URL above
223two more times (or refresh your browser twice if it still contains this
224URL):
225
226 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
227
228You should be able to click "Return to list" and now see 3 copies of
229"TCP_Illustrated_Vol-2".
230
4d583dd8 231
4d583dd8 232=head1 MANUALLY BUILDING A CREATE FORM
233
64ccd8a8 234Although the C<url_create> action in the previous step does begin to
235reveal the power and flexibility of both Catalyst and DBIC, it's
236obviously not a very realistic example of how users should be expected
237to enter data. This section begins to address that concern.
4d583dd8 238
239
240=head2 Add Method to Display The Form
241
242Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
243
244 =head2 form_create
245
246 Display form to collect information for book to create
247
248 =cut
249
250 sub form_create : Local {
251 my ($self, $c) = @_;
252
253 # Set the TT template to use
254 $c->stash->{template} = 'books/form_create.tt2';
255 }
256
71dedf57 257This action simply invokes a view containing a book creation form.
4d583dd8 258
259=head2 Add a Template for the Form
260
261Open C<root/src/books/form_create.tt2> in your editor and enter:
262
5c1f2a06 263 [% META title = 'Manual Form Book Create' -%]
4d583dd8 264
265 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
266 <table>
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>
270 </table>
271 <input type="submit" name="Submit" value="Submit">
272 </form>
273
64ccd8a8 274Note that we have specified the target of the form data as
275C<form_create_do>, the method created in the section that follows.
4d583dd8 276
f2c10d65 277=head2 Add a Method to Process Form Values and Update Database
4d583dd8 278
64ccd8a8 279Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
7d310f12 280save the form information to the database:
4d583dd8 281
282 =head2 form_create_do
283
284 Take information from form and add to database
285
286 =cut
287
288 sub form_create_do : Local {
289 my ($self, $c) = @_;
290
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';
295
296 # Create the book
297 my $book = $c->model('MyAppDB::Book')->create({
298 title => $title,
299 rating => $rating,
300 });
301 # Handle relationship with author
302 $book->add_to_book_authors({author_id => $author_id});
303
304 # Store new model object in stash
305 $c->stash->{book} = $book;
306
71dedf57 307 # Avoid Data::Dumper issue mentioned earlier
4d583dd8 308 # You can probably omit this
309 $Data::Dumper::Useperl = 1;
310
311 # Set the TT template to use
312 $c->stash->{template} = 'books/create_done.tt2';
313 }
314
315
316=head2 Test Out The Form
317
71dedf57 318If the application is still running from before, use C<Ctrl-C> to kill
319it. Then restart the server:
4d583dd8 320
321 $ script/myapp_server.pl
322
64ccd8a8 323Point your browser to L<http://localhost:3000/books/form_create> and
324enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
325author ID of 4. You should then be forwarded to the same
326C<create_done.tt2> template seen in earlier examples. Finally, click
327"Return to list" to view the full list of books.
4d583dd8 328
64ccd8a8 329B<Note:> Having the user enter the primary key ID for the author is
71dedf57 330obviously crude; we will address this concern with a drop-down list in
331Part 8.
4d583dd8 332
f2c10d65 333
4d583dd8 334=head1 A SIMPLE DELETE FEATURE
335
8112f931 336Turning our attention to the delete portion of CRUD, this section
64ccd8a8 337illustrates some basic techniques that can be used to remove information
338from the database.
4d583dd8 339
340
341=head2 Include a Delete Link in the List
342
64ccd8a8 343Edit C<root/src/books/list.tt2> and update it to the following (two
344sections have changed: 1) the additional '<th>Links</th>' table header,
345and 2) the four lines for the Delete link near the bottom).
4d583dd8 346
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. -%]
351
352 [% # Provide a title to root/lib/site/header -%]
353 [% META title = 'Book List' -%]
354
355 <table>
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 -%]
359 <tr>
360 <td>[% book.title %]</td>
361 <td>[% book.rating %]</td>
362 <td>
5c1f2a06 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 -%]
c9b77c06 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. -%]
5c1f2a06 370 [% tt_authors = [ ];
c9b77c06 371 tt_authors.push(author.last_name) FOREACH author = book.authors %]
f2c10d65 372 [% # Now use a TT 'virtual method' to display the author count in parens -%]
5c1f2a06 373 ([% tt_authors.size %])
c9b77c06 374 [% # Use another TT vmethod to join & print the names & comma separators -%]
5c1f2a06 375 [% tt_authors.join(', ') %]
4d583dd8 376 </td>
377 <td>
378 [% # Add a link to delete a book %]
379 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
380 </td>
381 </tr>
382 [% END -%]
383 </table>
384
64ccd8a8 385The additional code is obviously designed to add a new column to the
386right side of the table with a C<Delete> "button" (for simplicity, links
387will be used instead of full HTML buttons).
4d583dd8 388
4d583dd8 389=head2 Add a Delete Action to the Controller
390
64ccd8a8 391Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
392following method:
4d583dd8 393
cc548726 394 =head2 delete
4d583dd8 395
396 Delete a book
397
398 =cut
399
400 sub delete : Local {
401 # $id = primary key of book to delete
402 my ($self, $c, $id) = @_;
403
404 # Search for the book and then delete it
405 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
406
407 # Set a status message to be displayed at the top of the view
408 $c->stash->{status_msg} = "Book deleted.";
409
410 # Forward to the list action/method in this controller
411 $c->forward('list');
412 }
413
64ccd8a8 414This method first deletes the book with the specified primary key ID.
415However, it also removes the corresponding entry from the
416C<book_authors> table. Note that C<delete_all> was used instead of
417C<delete>: whereas C<delete_all> also removes the join table entries in
418C<book_authors>, C<delete> does not.
4d583dd8 419
64ccd8a8 420Then, rather than forwarding to a "delete done" page as we did with the
421earlier create example, it simply sets the C<status_msg> to display a
422notification to the user as the normal list view is rendered.
4d583dd8 423
64ccd8a8 424The C<delete> action uses the context C<forward> method to return the
425user to the book list. The C<detach> method could have also been used.
426Whereas C<forward> I<returns> to the original action once it is
427completed, C<detach> does I<not> return. Other than that, the two are
428equivalent.
4d583dd8 429
4d583dd8 430
431=head2 Try the Delete Feature
432
64ccd8a8 433If the application is still running from before, use C<Ctrl-C> to kill
434it. Then restart the server:
4d583dd8 435
436 $ script/myapp_server.pl
437
64ccd8a8 438Then point your browser to L<http://localhost:3000/books/list> and click
f2c10d65 439the "Delete" link next to the first "TCPIP_Illustrated_Vol-2". A green
440"Book deleted" status message should display at the top of the page,
441along with a list of the eight remaining books.
442
443
444=head2 Fixing a Dangerous URL
445
446Note the URL in your browser once you have performed the deleted in the
447prior step -- it is still referencing the delete action:
448
449 http://localhost:3000/books/delete/6
450
451What if the user were to press reload with this URL still active? In
452this case the redundant delete is harmless, but in other cases this
453could clearly be extremely dangerous.
454
455We can improve the logic by converting to a redirect. Unlike
456C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
457a server-side alteration in the flow of processing, a redirect is a
458client-side mechanism that causes the brower to issue an entirely
459new request. As a result, the URL in the browser is updated to match
460the destination of the redirection URL.
461
462To convert the forward used in the previous section to a redirect,
463open C<lib/MyApp/Controller/Books.pm> and the existing C<sub delete>
464method to match:
465
466 =head2 delete
467
468 Delete a book
469
470 =cut
471
472 sub delete : Local {
473 # $id = primary key of book to delete
474 my ($self, $c, $id) = @_;
475
476 # Search for the book and then delete it
477 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
478
479 # Set a status message to be displayed at the top of the view
480 $c->stash->{status_msg} = "Book deleted.";
481
482 # Redirect the user back to the list page
483 $c->response->redirect($c->uri_for('/books/list'));
484 }
485
486
487=head2 Try the Delete and Redirect Logic
488
489Restart the development server and point your browser to
490L<http://localhost:3000/books/list>. Delete the first copy of
491"TCPIP_Illustrated_Vol-2", but notice that I<no green "Book deleted"
492status message is displayed>. Because the stash is reset on every
493request, the C<status_msg> is cleared before it can be displayed.
494
495
496=head2 Using C<uri_for> to Pass Query Parameters
497
498There are several ways to pass information across a redirect.
499In general, the best option is to use the C<flash> technique that we
500will see in Part 4 of the tutorial; however, here we will pass the
501information via the redirect itself. Open
502C<lib/MyApp/Controller/Books.pm> and update the existing
503C<sub delete> method to match the following:
504
505 =head2 delete
506
507 Delete a book
508
509 =cut
510
511 sub delete : Local {
512 # $id = primary key of book to delete
513 my ($self, $c, $id) = @_;
514
515 # Search for the book and then delete it
516 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
517
518 # Redirect the user back to the list page with status msg as an arg
519 $c->response->redirect($c->uri_for('/books/list',
520 {status_msg => "Book deleted."}));
521 }
522
523This modification simply leverages the ability of C<uri_for> to include
524an arbitrary number of name/value pairs in a hash reference. Next, we
525need to update C<root/lib/site/layout> to handle C<status_msg> as a
526query parameter:
527
528 <div id="header">[% PROCESS site/header %]</div>
529
530 <div id="content">
531 <span class="message">[% status_msg || Catalyst.request.params.status_msg %]</span>
532 <span class="error">[% error_msg %]</span>
533 [% content %]
534 </div>
535
536 <div id="footer">[% PROCESS site/footer %]</div>
537
538
539=head2 Try the Delete and Redirect With Query Param Logic
540
541Restart the development server and point your browser to
542L<http://localhost:3000/books/list> and delete the remaining copy of
543"TCPIP_Illustrated_Vol-2". The green "Book deleted" status message
544should return.
545
546B<NOTE:> Although this did present an opportunity to show a handy
547capability of C<uri_for>, it would be much better to use Catalyst's
548C<flash> feature in this situation. Although less dangerous than
549leaving the delete URL in the client's browser, we have still exposed
550the status message to the user. With C<flash>, this message returns
551to its rightful place as a service-side mechanism (we will migrate
552this code to C<flash> in the next part of the tutorial).
4d583dd8 553
a63e6e67 554
4d583dd8 555=head1 AUTHOR
556
557Kennedy Clark, C<hkclark@gmail.com>
558
eed93301 559Please report any errors, issues or suggestions to the author. The
7d310f12 560most recent version of the Catalyst Tutorial can be found at
eed93301 561L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 562
64ccd8a8 563Copyright 2006, Kennedy Clark, under Creative Commons License
564(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
4d583dd8 565