Commit | Line | Data |
4d583dd8 |
1 | =head1 NAME |
2 | |
64ccd8a8 |
3 | Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD |
4d583dd8 |
4 | |
5 | |
6 | =head1 OVERVIEW |
7 | |
8 | This is B<Part 3 of 9> for the Catalyst tutorial. |
9 | |
64ccd8a8 |
10 | L<Tutorial Overview|Catalyst::Manual::Tutorial> |
4d583dd8 |
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 | |
7d310f12 |
48 | L<Appendices|Catalyst::Manual::Tutorial::Appendices> |
4d583dd8 |
49 | |
50 | =back |
51 | |
52 | |
53 | |
54 | =head1 DESCRIPTION |
55 | |
64ccd8a8 |
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 |
71dedf57 |
59 | 2 already implements the Read portion of CRUD (although Read normally |
64ccd8a8 |
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. |
4d583dd8 |
65 | |
936a5dd5 |
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> |
4d583dd8 |
69 | |
4d583dd8 |
70 | =head1 FORMLESS SUBMISSION |
71 | |
64ccd8a8 |
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). |
4d583dd8 |
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 | |
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 |
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. |
4d583dd8 |
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 | |
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 |
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. |
4d583dd8 |
176 | |
64ccd8a8 |
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>. |
4d583dd8 |
180 | |
4d583dd8 |
181 | =head2 Try the C<url_create> Feature |
182 | |
64ccd8a8 |
183 | If the application is still running from before, use C<Ctrl-C> to kill |
71dedf57 |
184 | it. Then restart the server: |
4d583dd8 |
185 | |
186 | $ script/myapp_server.pl |
187 | |
64ccd8a8 |
188 | Note that new path for C</books/url_create> appears in the startup debug |
189 | output. |
4d583dd8 |
190 | |
64ccd8a8 |
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 |
71dedf57 |
194 | the 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> |
196 | files require a reload). |
4d583dd8 |
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 | |
64ccd8a8 |
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: |
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' |
209 | |
64ccd8a8 |
210 | If you then click the "Return to list" link, you should find that there |
211 | are now six books shown (if necessary, Shift-Reload your browser at the |
212 | C</books/list> page). |
4d583dd8 |
213 | |
214 | |
4d583dd8 |
215 | =head1 MANUALLY BUILDING A CREATE FORM |
216 | |
64ccd8a8 |
217 | Although the C<url_create> action in the previous step does begin to |
218 | reveal the power and flexibility of both Catalyst and DBIC, it's |
219 | obviously not a very realistic example of how users should be expected |
220 | to enter data. This section begins to address that concern. |
4d583dd8 |
221 | |
222 | |
223 | =head2 Add Method to Display The Form |
224 | |
225 | Edit C<lib/MyApp/Controller/Books.pm> and add the following method: |
226 | |
227 | =head2 form_create |
228 | |
229 | Display form to collect information for book to create |
230 | |
231 | =cut |
232 | |
233 | sub form_create : Local { |
234 | my ($self, $c) = @_; |
235 | |
236 | # Set the TT template to use |
237 | $c->stash->{template} = 'books/form_create.tt2'; |
238 | } |
239 | |
71dedf57 |
240 | This action simply invokes a view containing a book creation form. |
4d583dd8 |
241 | |
242 | =head2 Add a Template for the Form |
243 | |
244 | Open C<root/src/books/form_create.tt2> in your editor and enter: |
245 | |
5c1f2a06 |
246 | [% META title = 'Manual Form Book Create' -%] |
4d583dd8 |
247 | |
248 | <form method="post" action="[% Catalyst.uri_for('form_create_do') %]"> |
249 | <table> |
250 | <tr><td>Title:</td><td><input type="text" name="title"></td></tr> |
251 | <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr> |
252 | <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr> |
253 | </table> |
254 | <input type="submit" name="Submit" value="Submit"> |
255 | </form> |
256 | |
64ccd8a8 |
257 | Note that we have specified the target of the form data as |
258 | C<form_create_do>, the method created in the section that follows. |
4d583dd8 |
259 | |
4d583dd8 |
260 | =head2 Add Method to Process Form Values and Update Database |
261 | |
64ccd8a8 |
262 | Edit C<lib/MyApp/Controller/Books.pm> and add the following method to |
7d310f12 |
263 | save the form information to the database: |
4d583dd8 |
264 | |
265 | =head2 form_create_do |
266 | |
267 | Take information from form and add to database |
268 | |
269 | =cut |
270 | |
271 | sub form_create_do : Local { |
272 | my ($self, $c) = @_; |
273 | |
274 | # Retrieve the values from the form |
275 | my $title = $c->request->params->{title} || 'N/A'; |
276 | my $rating = $c->request->params->{rating} || 'N/A'; |
277 | my $author_id = $c->request->params->{author_id} || '1'; |
278 | |
279 | # Create the book |
280 | my $book = $c->model('MyAppDB::Book')->create({ |
281 | title => $title, |
282 | rating => $rating, |
283 | }); |
284 | # Handle relationship with author |
285 | $book->add_to_book_authors({author_id => $author_id}); |
286 | |
287 | # Store new model object in stash |
288 | $c->stash->{book} = $book; |
289 | |
71dedf57 |
290 | # Avoid Data::Dumper issue mentioned earlier |
4d583dd8 |
291 | # You can probably omit this |
292 | $Data::Dumper::Useperl = 1; |
293 | |
294 | # Set the TT template to use |
295 | $c->stash->{template} = 'books/create_done.tt2'; |
296 | } |
297 | |
298 | |
299 | =head2 Test Out The Form |
300 | |
71dedf57 |
301 | If the application is still running from before, use C<Ctrl-C> to kill |
302 | it. Then restart the server: |
4d583dd8 |
303 | |
304 | $ script/myapp_server.pl |
305 | |
64ccd8a8 |
306 | Point your browser to L<http://localhost:3000/books/form_create> and |
307 | enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an |
308 | author ID of 4. You should then be forwarded to the same |
309 | C<create_done.tt2> template seen in earlier examples. Finally, click |
310 | "Return to list" to view the full list of books. |
4d583dd8 |
311 | |
64ccd8a8 |
312 | B<Note:> Having the user enter the primary key ID for the author is |
71dedf57 |
313 | obviously crude; we will address this concern with a drop-down list in |
314 | Part 8. |
4d583dd8 |
315 | |
316 | =head1 A SIMPLE DELETE FEATURE |
317 | |
8112f931 |
318 | Turning our attention to the delete portion of CRUD, this section |
64ccd8a8 |
319 | illustrates some basic techniques that can be used to remove information |
320 | from the database. |
4d583dd8 |
321 | |
322 | |
323 | =head2 Include a Delete Link in the List |
324 | |
64ccd8a8 |
325 | Edit C<root/src/books/list.tt2> and update it to the following (two |
326 | sections have changed: 1) the additional '<th>Links</th>' table header, |
327 | and 2) the four lines for the Delete link near the bottom). |
4d583dd8 |
328 | |
329 | [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%] |
330 | [% # see this "chomping" in your browser because HTML ignores blank lines, but -%] |
331 | [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%] |
332 | [%- # optional, but both the beginning and the ending TT tags support chomping. -%] |
333 | |
334 | [% # Provide a title to root/lib/site/header -%] |
335 | [% META title = 'Book List' -%] |
336 | |
337 | <table> |
338 | <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr> |
339 | [% # Display each book in a table row %] |
340 | [% FOREACH book IN books -%] |
341 | <tr> |
342 | <td>[% book.title %]</td> |
343 | <td>[% book.rating %]</td> |
344 | <td> |
5c1f2a06 |
345 | [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%] |
346 | [% # loop in 'side effect notation' to load just the last names of the -%] |
c9b77c06 |
347 | [% # authors into the list. Note that the 'push' TT vmethod does not -%] |
348 | [% # a value, so nothing will be printed here. But, if you have something -%] |
349 | [% # in TT that does return a method and you don't want it printed, you -%] |
350 | [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%] |
351 | [% # call it and discard the return value. -%] |
5c1f2a06 |
352 | [% tt_authors = [ ]; |
c9b77c06 |
353 | tt_authors.push(author.last_name) FOREACH author = book.authors %] |
5c1f2a06 |
354 | [% # Now use a TT 'virtual method' to display the author count -%] |
355 | ([% tt_authors.size %]) |
c9b77c06 |
356 | [% # Use another TT vmethod to join & print the names & comma separators -%] |
5c1f2a06 |
357 | [% tt_authors.join(', ') %] |
4d583dd8 |
358 | </td> |
359 | <td> |
360 | [% # Add a link to delete a book %] |
361 | <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a> |
362 | </td> |
363 | </tr> |
364 | [% END -%] |
365 | </table> |
366 | |
64ccd8a8 |
367 | The additional code is obviously designed to add a new column to the |
368 | right side of the table with a C<Delete> "button" (for simplicity, links |
369 | will be used instead of full HTML buttons). |
4d583dd8 |
370 | |
4d583dd8 |
371 | =head2 Add a Delete Action to the Controller |
372 | |
64ccd8a8 |
373 | Open C<lib/MyApp/Controller/Books.pm> in your editor and add the |
374 | following method: |
4d583dd8 |
375 | |
cc548726 |
376 | =head2 delete |
4d583dd8 |
377 | |
378 | Delete a book |
379 | |
380 | =cut |
381 | |
382 | sub delete : Local { |
383 | # $id = primary key of book to delete |
384 | my ($self, $c, $id) = @_; |
385 | |
386 | # Search for the book and then delete it |
387 | $c->model('MyAppDB::Book')->search({id => $id})->delete_all; |
388 | |
389 | # Set a status message to be displayed at the top of the view |
390 | $c->stash->{status_msg} = "Book deleted."; |
391 | |
392 | # Forward to the list action/method in this controller |
393 | $c->forward('list'); |
394 | } |
395 | |
64ccd8a8 |
396 | This method first deletes the book with the specified primary key ID. |
397 | However, it also removes the corresponding entry from the |
398 | C<book_authors> table. Note that C<delete_all> was used instead of |
399 | C<delete>: whereas C<delete_all> also removes the join table entries in |
400 | C<book_authors>, C<delete> does not. |
4d583dd8 |
401 | |
64ccd8a8 |
402 | Then, rather than forwarding to a "delete done" page as we did with the |
403 | earlier create example, it simply sets the C<status_msg> to display a |
404 | notification to the user as the normal list view is rendered. |
4d583dd8 |
405 | |
64ccd8a8 |
406 | The C<delete> action uses the context C<forward> method to return the |
407 | user to the book list. The C<detach> method could have also been used. |
408 | Whereas C<forward> I<returns> to the original action once it is |
409 | completed, C<detach> does I<not> return. Other than that, the two are |
410 | equivalent. |
4d583dd8 |
411 | |
64ccd8a8 |
412 | Another alternative to C<forward> would be to use |
413 | C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The |
414 | C<forward> and C<redirect> operations differ in several important |
415 | respects that stem from the fact that redirects cause the client browser |
416 | to issue an entirely new HTTP request. In doing so, this results in a |
417 | new URL showing in the browser window. And, because the stash |
418 | information is reset for every request, the "Book deleted" message would |
419 | not be displayed. |
4d583dd8 |
420 | |
421 | |
422 | =head2 Try the Delete Feature |
423 | |
64ccd8a8 |
424 | If the application is still running from before, use C<Ctrl-C> to kill |
425 | it. Then restart the server: |
4d583dd8 |
426 | |
427 | $ script/myapp_server.pl |
428 | |
64ccd8a8 |
429 | Then point your browser to L<http://localhost:3000/books/list> and click |
430 | the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book |
431 | deleted" status message should display at the top of the page, along |
432 | with a list of the six remaining books. |
4d583dd8 |
433 | |
a63e6e67 |
434 | |
4d583dd8 |
435 | =head1 AUTHOR |
436 | |
437 | Kennedy Clark, C<hkclark@gmail.com> |
438 | |
eed93301 |
439 | Please report any errors, issues or suggestions to the author. The |
7d310f12 |
440 | most recent version of the Catalyst Tutorial can be found at |
eed93301 |
441 | L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>. |
4d583dd8 |
442 | |
64ccd8a8 |
443 | Copyright 2006, Kennedy Clark, under Creative Commons License |
444 | (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>). |
4d583dd8 |
445 | |