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 | |
48 | L<Appendicies|Catalyst::Manual::Tutorial::Appendicies> |
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 | |
64ccd8a8 |
66 | B<TIP>: Note that all of the code for this part of the tutorial can be |
67 | pulled from the Catalyst Subversion repository in one step with the |
68 | following command: |
4d583dd8 |
69 | |
70 | svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@### |
71 | IMPORTANT: Does not work yet. Will be completed for final version. |
72 | |
73 | |
4d583dd8 |
74 | =head1 FORMLESS SUBMISSION |
75 | |
64ccd8a8 |
76 | Our initial attempt at object creation will utilize the "URL arguments" |
77 | feature of Catalyst (we will employ the more common form-based |
78 | submission in the sections that follow). |
4d583dd8 |
79 | |
80 | |
81 | =head2 Include a Create Action in the Books Controller |
82 | |
83 | Edit C<lib/MyApp/Controller/Books.pm> and enter the following method: |
84 | |
85 | =head2 url_create |
86 | |
71dedf57 |
87 | Create a book with the supplied title, rating, and author |
4d583dd8 |
88 | |
89 | =cut |
90 | |
91 | sub url_create : Local { |
71dedf57 |
92 | # In addition to self & context, get the title, rating, & |
93 | # author_id args from the URL. Note that Catalyst automatically |
94 | # puts extra information after the "/<controller_name>/<action_name/" |
95 | # into @_ |
4d583dd8 |
96 | my ($self, $c, $title, $rating, $author_id) = @_; |
97 | |
98 | # Call create() on the book model object. Pass the table |
99 | # columns/field values we want to set as hash values |
100 | my $book = $c->model('MyAppDB::Book')->create({ |
5c1f2a06 |
101 | title => $title, |
102 | rating => $rating |
4d583dd8 |
103 | }); |
104 | |
105 | # Add a record to the join table for this book, mapping to |
106 | # appropriate author |
107 | $book->add_to_book_authors({author_id => $author_id}); |
108 | # Note: Above is a shortcut for this: |
109 | # $book->create_related('book_authors', {author_id => $author_id}); |
110 | |
111 | # Assign the Book object to the stash for display in the view |
112 | $c->stash->{book} = $book; |
113 | |
114 | # This is a hack to disable XSUB processing in Data::Dumper |
115 | # (it's used in the view). This is a work-around for a bug in |
116 | # the interaction of some versions or Perl, Data::Dumper & DBIC. |
117 | # You won't need this if you aren't using Data::Dumper (or if |
118 | # you are running DBIC 0.06001 or greater), but adding it doesn't |
119 | # hurt anything either. |
120 | $Data::Dumper::Useperl = 1; |
121 | |
122 | # Set the TT template to use |
123 | $c->stash->{template} = 'books/create_done.tt2'; |
124 | } |
125 | |
64ccd8a8 |
126 | Notice that Catalyst takes "extra slash-separated information" from the |
127 | URL and passes it as arguments in C<@_>. The C<url_create> action then |
128 | uses a simple call to the DBIC C<create> method to add the requested |
129 | information to the database (with a separate call to |
130 | C<add_to_book_authors> to update the join table). As do virtually all |
131 | controller methods (at least the ones that directly handle user input), |
132 | it then sets the template that should handle this request. |
4d583dd8 |
133 | |
134 | |
135 | =head2 Include a Template for the C<url_create> Action: |
136 | |
137 | Edit C<root/src/books/create_done.tt2> and then enter: |
138 | |
139 | [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%] |
140 | [% # Not a good idea for production use, though. :-) 'Indent=1' is -%] |
141 | [% # optional, but prevents "massive indenting" of deeply nested objects -%] |
142 | [% USE Dumper(Indent=1) -%] |
143 | |
5c1f2a06 |
144 | [% # Set the page title. META can 'go back' and set values in templates -%] |
145 | [% # that have been processed 'before' this template (here it's for -%] |
146 | [% # root/lib/site/html and root/lib/site/header). Note that META on -%] |
147 | [% # simple strings (e.g., no variable interpolation). -%] |
4d583dd8 |
148 | [% META title = 'Book Created' %] |
149 | |
150 | [% # Output information about the record that was added. Note use -%] |
cc548726 |
151 | [% # of 'first' to only list the first author (if > 1 author). TT -%] |
152 | [% # v2.15 has an issue that requires -%] |
153 | [% # 'book.authors.list.first.value.last_name' vs. the shorter -%] |
154 | [% # 'book.authors.first.last_name' in prior versions. -%] |
155 | <p>Added book '[% book.title %]' |
156 | by '[% book.authors.list.first.value.last_name %]' |
4d583dd8 |
157 | with a rating of [% book.rating %].</p> |
158 | |
159 | [% # Provide a link back to the list page -%] |
160 | [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%] |
161 | <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p> |
162 | |
71dedf57 |
163 | [% # Try out the TT Dumper (for development only!) -%] |
4d583dd8 |
164 | <pre> |
165 | Dump of the 'book' variable: |
166 | [% Dumper.dump(book) %] |
167 | </pre> |
168 | |
71dedf57 |
169 | The TT C<USE> directive allows access to a variety of plugin modules (TT |
170 | plugins, that is, not Catalyst plugins) to add extra functionality to |
171 | the base TT capabilities. Here, the plugin allows L<Data::Dumper> |
172 | "pretty printing" of objects and variables. Other than that, the rest |
173 | of the code should be familiar from the examples in Part 2. |
4d583dd8 |
174 | |
64ccd8a8 |
175 | B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view |
176 | class created by TTSite redefines the name used to access the Catalyst |
177 | context object in TT templates from the usual C<c> to C<Catalyst>. |
4d583dd8 |
178 | |
4d583dd8 |
179 | =head2 Try the C<url_create> Feature |
180 | |
64ccd8a8 |
181 | If the application is still running from before, use C<Ctrl-C> to kill |
71dedf57 |
182 | it. Then restart the server: |
4d583dd8 |
183 | |
184 | $ script/myapp_server.pl |
185 | |
64ccd8a8 |
186 | Note that new path for C</books/url_create> appears in the startup debug |
187 | output. |
4d583dd8 |
188 | |
64ccd8a8 |
189 | B<TIP>: You can use C<script/myapp_server.pl -r> to have the development |
190 | server auto-detect changed files and reload itself (if your browser acts |
191 | odd, you should also try throwing in a C<-k>). If you make changes to |
71dedf57 |
192 | the TT templates only, you do not need to reload the development server |
64ccd8a8 |
193 | (only changes to "compiled code" such as Controller and Model C<.pm> |
194 | files require a reload). |
4d583dd8 |
195 | |
196 | Next, use your browser to enter the following URL: |
197 | |
198 | http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4 |
199 | |
64ccd8a8 |
200 | Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by |
201 | 'Stevens' with a rating of 5." along with a dump of the new book model |
202 | object. You should also see the following DBIC debug messages displayed |
203 | in the development server log messages: |
4d583dd8 |
204 | |
205 | INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2' |
206 | INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6' |
207 | |
64ccd8a8 |
208 | If you then click the "Return to list" link, you should find that there |
209 | are now six books shown (if necessary, Shift-Reload your browser at the |
210 | C</books/list> page). |
4d583dd8 |
211 | |
212 | |
4d583dd8 |
213 | =head1 MANUALLY BUILDING A CREATE FORM |
214 | |
64ccd8a8 |
215 | Although the C<url_create> action in the previous step does begin to |
216 | reveal the power and flexibility of both Catalyst and DBIC, it's |
217 | obviously not a very realistic example of how users should be expected |
218 | to enter data. This section begins to address that concern. |
4d583dd8 |
219 | |
220 | |
221 | =head2 Add Method to Display The Form |
222 | |
223 | Edit C<lib/MyApp/Controller/Books.pm> and add the following method: |
224 | |
225 | =head2 form_create |
226 | |
227 | Display form to collect information for book to create |
228 | |
229 | =cut |
230 | |
231 | sub form_create : Local { |
232 | my ($self, $c) = @_; |
233 | |
234 | # Set the TT template to use |
235 | $c->stash->{template} = 'books/form_create.tt2'; |
236 | } |
237 | |
71dedf57 |
238 | This action simply invokes a view containing a book creation form. |
4d583dd8 |
239 | |
240 | =head2 Add a Template for the Form |
241 | |
242 | Open C<root/src/books/form_create.tt2> in your editor and enter: |
243 | |
5c1f2a06 |
244 | [% META title = 'Manual Form Book Create' -%] |
4d583dd8 |
245 | |
246 | <form method="post" action="[% Catalyst.uri_for('form_create_do') %]"> |
247 | <table> |
248 | <tr><td>Title:</td><td><input type="text" name="title"></td></tr> |
249 | <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr> |
250 | <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr> |
251 | </table> |
252 | <input type="submit" name="Submit" value="Submit"> |
253 | </form> |
254 | |
64ccd8a8 |
255 | Note that we have specified the target of the form data as |
256 | C<form_create_do>, the method created in the section that follows. |
4d583dd8 |
257 | |
4d583dd8 |
258 | =head2 Add Method to Process Form Values and Update Database |
259 | |
64ccd8a8 |
260 | Edit C<lib/MyApp/Controller/Books.pm> and add the following method to |
261 | save the form information to the databse: |
4d583dd8 |
262 | |
263 | =head2 form_create_do |
264 | |
265 | Take information from form and add to database |
266 | |
267 | =cut |
268 | |
269 | sub form_create_do : Local { |
270 | my ($self, $c) = @_; |
271 | |
272 | # Retrieve the values from the form |
273 | my $title = $c->request->params->{title} || 'N/A'; |
274 | my $rating = $c->request->params->{rating} || 'N/A'; |
275 | my $author_id = $c->request->params->{author_id} || '1'; |
276 | |
277 | # Create the book |
278 | my $book = $c->model('MyAppDB::Book')->create({ |
279 | title => $title, |
280 | rating => $rating, |
281 | }); |
282 | # Handle relationship with author |
283 | $book->add_to_book_authors({author_id => $author_id}); |
284 | |
285 | # Store new model object in stash |
286 | $c->stash->{book} = $book; |
287 | |
71dedf57 |
288 | # Avoid Data::Dumper issue mentioned earlier |
4d583dd8 |
289 | # You can probably omit this |
290 | $Data::Dumper::Useperl = 1; |
291 | |
292 | # Set the TT template to use |
293 | $c->stash->{template} = 'books/create_done.tt2'; |
294 | } |
295 | |
296 | |
297 | =head2 Test Out The Form |
298 | |
71dedf57 |
299 | If the application is still running from before, use C<Ctrl-C> to kill |
300 | it. Then restart the server: |
4d583dd8 |
301 | |
302 | $ script/myapp_server.pl |
303 | |
64ccd8a8 |
304 | Point your browser to L<http://localhost:3000/books/form_create> and |
305 | enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an |
306 | author ID of 4. You should then be forwarded to the same |
307 | C<create_done.tt2> template seen in earlier examples. Finally, click |
308 | "Return to list" to view the full list of books. |
4d583dd8 |
309 | |
64ccd8a8 |
310 | B<Note:> Having the user enter the primary key ID for the author is |
71dedf57 |
311 | obviously crude; we will address this concern with a drop-down list in |
312 | Part 8. |
4d583dd8 |
313 | |
314 | =head1 A SIMPLE DELETE FEATURE |
315 | |
64ccd8a8 |
316 | Turning out attention to the delete portion of CRUD, this section |
317 | illustrates some basic techniques that can be used to remove information |
318 | from the database. |
4d583dd8 |
319 | |
320 | |
321 | =head2 Include a Delete Link in the List |
322 | |
64ccd8a8 |
323 | Edit C<root/src/books/list.tt2> and update it to the following (two |
324 | sections have changed: 1) the additional '<th>Links</th>' table header, |
325 | and 2) the four lines for the Delete link near the bottom). |
4d583dd8 |
326 | |
327 | [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%] |
328 | [% # see this "chomping" in your browser because HTML ignores blank lines, but -%] |
329 | [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%] |
330 | [%- # optional, but both the beginning and the ending TT tags support chomping. -%] |
331 | |
332 | [% # Provide a title to root/lib/site/header -%] |
333 | [% META title = 'Book List' -%] |
334 | |
335 | <table> |
336 | <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr> |
337 | [% # Display each book in a table row %] |
338 | [% FOREACH book IN books -%] |
339 | <tr> |
340 | <td>[% book.title %]</td> |
341 | <td>[% book.rating %]</td> |
342 | <td> |
5c1f2a06 |
343 | [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%] |
344 | [% # loop in 'side effect notation' to load just the last names of the -%] |
345 | [% # authors into the list. Note that we are making a bogus assignment to -%] |
346 | [% # the 'xx' vbl to avoid printing the size of the list after each push. -%] |
347 | [% tt_authors = [ ]; |
348 | xx = tt_authors.push(author.last_name) FOREACH author = book.authors %] |
349 | [% # Now use a TT 'virtual method' to display the author count -%] |
350 | ([% tt_authors.size %]) |
351 | [% # Use another TT virtual method to join the names with comma separators -%] |
352 | [% tt_authors.join(', ') %] |
4d583dd8 |
353 | </td> |
354 | <td> |
355 | [% # Add a link to delete a book %] |
356 | <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a> |
357 | </td> |
358 | </tr> |
359 | [% END -%] |
360 | </table> |
361 | |
64ccd8a8 |
362 | The additional code is obviously designed to add a new column to the |
363 | right side of the table with a C<Delete> "button" (for simplicity, links |
364 | will be used instead of full HTML buttons). |
4d583dd8 |
365 | |
4d583dd8 |
366 | =head2 Add a Delete Action to the Controller |
367 | |
64ccd8a8 |
368 | Open C<lib/MyApp/Controller/Books.pm> in your editor and add the |
369 | following method: |
4d583dd8 |
370 | |
cc548726 |
371 | =head2 delete |
4d583dd8 |
372 | |
373 | Delete a book |
374 | |
375 | =cut |
376 | |
377 | sub delete : Local { |
378 | # $id = primary key of book to delete |
379 | my ($self, $c, $id) = @_; |
380 | |
381 | # Search for the book and then delete it |
382 | $c->model('MyAppDB::Book')->search({id => $id})->delete_all; |
383 | |
384 | # Set a status message to be displayed at the top of the view |
385 | $c->stash->{status_msg} = "Book deleted."; |
386 | |
387 | # Forward to the list action/method in this controller |
388 | $c->forward('list'); |
389 | } |
390 | |
64ccd8a8 |
391 | This method first deletes the book with the specified primary key ID. |
392 | However, it also removes the corresponding entry from the |
393 | C<book_authors> table. Note that C<delete_all> was used instead of |
394 | C<delete>: whereas C<delete_all> also removes the join table entries in |
395 | C<book_authors>, C<delete> does not. |
4d583dd8 |
396 | |
64ccd8a8 |
397 | Then, rather than forwarding to a "delete done" page as we did with the |
398 | earlier create example, it simply sets the C<status_msg> to display a |
399 | notification to the user as the normal list view is rendered. |
4d583dd8 |
400 | |
64ccd8a8 |
401 | The C<delete> action uses the context C<forward> method to return the |
402 | user to the book list. The C<detach> method could have also been used. |
403 | Whereas C<forward> I<returns> to the original action once it is |
404 | completed, C<detach> does I<not> return. Other than that, the two are |
405 | equivalent. |
4d583dd8 |
406 | |
64ccd8a8 |
407 | Another alternative to C<forward> would be to use |
408 | C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The |
409 | C<forward> and C<redirect> operations differ in several important |
410 | respects that stem from the fact that redirects cause the client browser |
411 | to issue an entirely new HTTP request. In doing so, this results in a |
412 | new URL showing in the browser window. And, because the stash |
413 | information is reset for every request, the "Book deleted" message would |
414 | not be displayed. |
4d583dd8 |
415 | |
416 | |
417 | =head2 Try the Delete Feature |
418 | |
64ccd8a8 |
419 | If the application is still running from before, use C<Ctrl-C> to kill |
420 | it. Then restart the server: |
4d583dd8 |
421 | |
422 | $ script/myapp_server.pl |
423 | |
64ccd8a8 |
424 | Then point your browser to L<http://localhost:3000/books/list> and click |
425 | the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book |
426 | deleted" status message should display at the top of the page, along |
427 | with a list of the six remaining books. |
4d583dd8 |
428 | |
a63e6e67 |
429 | |
4d583dd8 |
430 | =head1 AUTHOR |
431 | |
432 | Kennedy Clark, C<hkclark@gmail.com> |
433 | |
eed93301 |
434 | Please report any errors, issues or suggestions to the author. The |
435 | most recent version of the Catlayst Tutorial can be found at |
436 | L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>. |
4d583dd8 |
437 | |
64ccd8a8 |
438 | Copyright 2006, Kennedy Clark, under Creative Commons License |
439 | (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>). |
4d583dd8 |
440 | |