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