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