Fix typo (thanks to David Steiner)
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / BasicCRUD.pod
CommitLineData
d442cc9f 1=head1 NAME
2
3533daff 3Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 4: Basic CRUD
d442cc9f 4
5
6=head1 OVERVIEW
7
3533daff 8This is B<Part 4 of 10> for the Catalyst tutorial.
d442cc9f 9
10L<Tutorial Overview|Catalyst::Manual::Tutorial>
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
3533daff 24L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
d442cc9f 25
26=item 4
27
3533daff 28B<Basic CRUD>
d442cc9f 29
30=item 5
31
3533daff 32L<Authentication|Catalyst::Manual::Tutorial::Authentication>
d442cc9f 33
34=item 6
35
3533daff 36L<Authorization|Catalyst::Manual::Tutorial::Authorization>
d442cc9f 37
38=item 7
39
3533daff 40L<Debugging|Catalyst::Manual::Tutorial::Debugging>
d442cc9f 41
42=item 8
43
3533daff 44L<Testing|Catalyst::Manual::Tutorial::Testing>
d442cc9f 45
46=item 9
47
3533daff 48L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49
50=item 10
51
d442cc9f 52L<Appendices|Catalyst::Manual::Tutorial::Appendices>
53
54=back
55
56
d442cc9f 57=head1 DESCRIPTION
58
59This part of the tutorial builds on the fairly primitive application
3533daff 60created in Part 3 to add basic support for Create, Read, Update, and
d442cc9f 61Delete (CRUD) of C<Book> objects. Note that the 'list' function in Part
622 already implements the Read portion of CRUD (although Read normally
63refers to reading a single object; you could implement full read
64functionality using the techniques introduced below). This section will
65focus on the Create and Delete aspects of CRUD. More advanced
66capabilities, including full Update functionality, will be addressed in
3533daff 67Part 9.
d442cc9f 68
1390ef0e 69Although this part of the tutorial will show you how to build CRUD
70functionality yourself, another option is to use a "CRUD builder" type
71of tool to automate the process. You get less control, but it's quick
72and easy. For example, see
73L<CatalystX::ListFramework::Builder|CatalystX::ListFramework::Builder>,
74L<CatalystX::CRUD|CatalystX::CRUD>, and
7edc5484 75L<CatalystX::CRUD::YUI|CatalystX::CRUD::YUI>.
1390ef0e 76
d442cc9f 77You can checkout the source code for this example from the catalyst
78subversion repository as per the instructions in
1390ef0e 79L<Catalyst::Manual::Tutorial::Intro|Catalyst::Manual::Tutorial::Intro>.
d442cc9f 80
3533daff 81
d442cc9f 82=head1 FORMLESS SUBMISSION
83
3533daff 84Our initial attempt at object creation will utilize the "URL
85arguments" feature of Catalyst (we will employ the more common form-
86based submission in the sections that follow).
d442cc9f 87
88
89=head2 Include a Create Action in the Books Controller
90
91Edit 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
d0496197 108 my $book = $c->model('DB::Books')->create({
d442cc9f 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
134Notice that Catalyst takes "extra slash-separated information" from the
135URL and passes it as arguments in C<@_>. The C<url_create> action then
136uses a simple call to the DBIC C<create> method to add the requested
137information to the database (with a separate call to
138C<add_to_book_authors> to update the join table). As do virtually all
139controller methods (at least the ones that directly handle user input),
140it then sets the template that should handle this request.
141
142
143=head2 Include a Template for the C<url_create> Action:
144
145Edit 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' -%]
8a7c5151 175 <p><a href="[% c.uri_for('/books/list') %]">Return to list</a></p>
d442cc9f 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
1390ef0e 183The TT C<USE> directive allows access to a variety of plugin modules
184(TT plugins, that is, not Catalyst plugins) to add extra functionality
185to the base TT capabilities. Here, the plugin allows
186L<Data::Dumper|Data::Dumper> "pretty printing" of objects and
187variables. Other than that, the rest of the code should be familiar
188from the examples in Part 3.
d442cc9f 189
d442cc9f 190
191=head2 Try the C<url_create> Feature
192
193If the application is still running from before, use C<Ctrl-C> to kill
194it. Then restart the server:
195
1390ef0e 196 $ DBIC_TRACE=1 script/myapp_server.pl
d442cc9f 197
198Note that new path for C</books/url_create> appears in the startup debug
199output.
200
201B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
202server auto-detect changed files and reload itself (if your browser acts
203odd, you should also try throwing in a C<-k>). If you make changes to
204the 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>
206files require a reload).
207
208Next, use your browser to enter the following URL:
209
210 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
211
212Your 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
214object. You should also see the following DBIC debug messages displayed
3533daff 215in the development server log messages if you have DBIC_TRACE set:
d442cc9f 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
223The C<INSERT> statements are obviously adding the book and linking it to
224the existing record for Richard Stevens. The C<SELECT> statement results
225from DBIC automatically fetching the book for the C<Dumper.dump(book)>.
226
1390ef0e 227If you then click the "Return to list" link, you should find that
228there are now six books shown (if necessary, Shift+Reload or
229Ctrl+Reload your browser at the C</books/list> page).
d442cc9f 230
231Then I<add 2 more copies of the same book> so that we have some extras for
232our delete logic that will be coming up soon. Enter the same URL above
233two more times (or refresh your browser twice if it still contains this
234URL):
235
236 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
237
238You 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
244Although the C<url_create> action in the previous step does begin to
245reveal the power and flexibility of both Catalyst and DBIC, it's
246obviously not a very realistic example of how users should be expected
247to enter data. This section begins to address that concern.
248
249
250=head2 Add Method to Display The Form
251
252Edit 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
267This action simply invokes a view containing a book creation form.
268
1390ef0e 269
d442cc9f 270=head2 Add a Template for the Form
271
272Open C<root/src/books/form_create.tt2> in your editor and enter:
273
274 [% META title = 'Manual Form Book Create' -%]
275
8a7c5151 276 <form method="post" action="[% c.uri_for('form_create_do') %]">
d442cc9f 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
285Note that we have specified the target of the form data as
286C<form_create_do>, the method created in the section that follows.
287
1390ef0e 288
d442cc9f 289=head2 Add a Method to Process Form Values and Update Database
290
291Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
292save 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
d0496197 309 my $book = $c->model('DB::Books')->create({
d442cc9f 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
330If the application is still running from before, use C<Ctrl-C> to kill
331it. Then restart the server:
332
333 $ script/myapp_server.pl
334
335Point your browser to L<http://localhost:3000/books/form_create> and
336enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
1390ef0e 337author ID of 4. You should then see the output of the same
d442cc9f 338C<create_done.tt2> template seen in earlier examples. Finally, click
339"Return to list" to view the full list of books.
340
341B<Note:> Having the user enter the primary key ID for the author is
342obviously crude; we will address this concern with a drop-down list in
3533daff 343Part 9.
d442cc9f 344
345
346=head1 A SIMPLE DELETE FEATURE
347
348Turning our attention to the delete portion of CRUD, this section
349illustrates some basic techniques that can be used to remove information
350from the database.
351
352
353=head2 Include a Delete Link in the List
354
355Edit C<root/src/books/list.tt2> and update it to the following (two
356sections have changed: 1) the additional '<th>Links</th>' table header,
357and 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 %]
8a7c5151 391 <a href="[% c.uri_for('delete', book.id) %]">Delete</a>
d442cc9f 392 </td>
393 </tr>
394 [% END -%]
395 </table>
396
397The additional code is obviously designed to add a new column to the
398right side of the table with a C<Delete> "button" (for simplicity, links
399will be used instead of full HTML buttons).
400
1390ef0e 401
d442cc9f 402=head2 Add a Delete Action to the Controller
403
404Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
405following method:
406
1390ef0e 407 =head2 delete
d442cc9f 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
d0496197 418 $c->model('DB::Books')->search({id => $id})->delete_all;
d442cc9f 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
427This method first deletes the book with the specified primary key ID.
428However, it also removes the corresponding entry from the
429C<book_authors> table. Note that C<delete_all> was used instead of
430C<delete>: whereas C<delete_all> also removes the join table entries in
431C<book_authors>, C<delete> does not (only use C<delete_all> if you
432really need the cascading deletes... otherwise you are wasting resources).
433
434Then, rather than forwarding to a "delete done" page as we did with the
435earlier create example, it simply sets the C<status_msg> to display a
436notification to the user as the normal list view is rendered.
437
438The C<delete> action uses the context C<forward> method to return the
439user to the book list. The C<detach> method could have also been used.
440Whereas C<forward> I<returns> to the original action once it is
441completed, C<detach> does I<not> return. Other than that, the two are
442equivalent.
443
444
445=head2 Try the Delete Feature
446
447If the application is still running from before, use C<Ctrl-C> to kill
448it. Then restart the server:
449
450 $ script/myapp_server.pl
451
452Then point your browser to L<http://localhost:3000/books/list> and click
453the "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,
455along with a list of the eight remaining books.
456
457
458=head2 Fixing a Dangerous URL
459
5edc2aae 460Note the URL in your browser once you have performed the deletion in the
d442cc9f 461prior step -- it is still referencing the delete action:
462
463 http://localhost:3000/books/delete/6
464
465What if the user were to press reload with this URL still active? In
466this case the redundant delete is harmless, but in other cases this
467could clearly be extremely dangerous.
468
469We can improve the logic by converting to a redirect. Unlike
470C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
471a server-side alteration in the flow of processing, a redirect is a
3533daff 472client-side mechanism that causes the browser to issue an entirely
d442cc9f 473new request. As a result, the URL in the browser is updated to match
474the destination of the redirection URL.
475
476To convert the forward used in the previous section to a redirect,
477open C<lib/MyApp/Controller/Books.pm> and edit the existing
478C<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
d0496197 491 $c->model('DB::Books')->search({id => $id})->delete_all;
d442cc9f 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
503Restart the development server and point your browser to
3533daff 504L<http://localhost:3000/books/list> and delete the first copy of
505"TCPIP_Illustrated_Vol-2". The URL in your browser should return to
506the L<http://localhost:3000/books/list> URL, so that is an
507improvement, but notice that I<no green "Book deleted" status message
508is displayed>. Because the stash is reset on every request (and a
509redirect involves a second request), the C<status_msg> is cleared
510before it can be displayed.
d442cc9f 511
512
513=head2 Using C<uri_for> to Pass Query Parameters
514
515There are several ways to pass information across a redirect.
516In general, the best option is to use the C<flash> technique that we
3533daff 517will see in Part 5 of the tutorial; however, here we will pass the
d442cc9f 518information via query parameters on the redirect itself. Open
519C<lib/MyApp/Controller/Books.pm> and update the existing
520C<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
d0496197 533 $c->model('DB::Books')->search({id => $id})->delete_all;
d442cc9f 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
540This modification simply leverages the ability of C<uri_for> to include
541an arbitrary number of name/value pairs in a hash reference. Next, we
1390ef0e 542need to update C<root/src/wrapper> to handle C<status_msg> as a
d442cc9f 543query parameter:
544
1390ef0e 545 ...
d442cc9f 546 <div id="content">
1390ef0e 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
555Although the sample above only shows the C<content> div, leave the
556rest of the file intact -- the only change we made to the C<wrapper.tt2>
557was to add "C<|| c.request.params.status_msg>" to the
558C<E<lt>span class="message"E<gt>> line.
d442cc9f 559
560
561=head2 Try the Delete and Redirect With Query Param Logic
562
563Restart the development server and point your browser to
564L<http://localhost:3000/books/list>. Then delete the remaining copy
565of "TCPIP_Illustrated_Vol-2". The green "Book deleted" status message
566should return.
567
568B<NOTE:> Although this did present an opportunity to show a handy
569capability of C<uri_for>, it would be much better to use Catalyst's
570C<flash> feature in this situation. Although the technique here is
571less dangerous than leaving the delete URL in the client's browser,
572we have still exposed the status message to the user. With C<flash>,
573this message returns to its rightful place as a service-side
574mechanism (we will migrate this code to C<flash> in the next part
575of the tutorial).
576
577
578=head1 AUTHOR
579
580Kennedy Clark, C<hkclark@gmail.com>
581
582Please report any errors, issues or suggestions to the author. The
583most recent version of the Catalyst Tutorial can be found at
82ab4bbf 584L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
d442cc9f 585
45c7830f 586Copyright 2006-2008, Kennedy Clark, under Creative Commons License
95674086 587(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).
d442cc9f 588