initial import of new Tutorial stuff from hkclark
[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
7 =head1 OVERVIEW
8
9 This is B<Part 3 of 9> for the Catalyst tutorial.
10
11 L<Totorial Overview|Catalyst::Manual::Tutorial>
12
13 =over 4
14
15 =item 1
16
17 L<Introduction|Catalyst::Manual::Tutorial::Intro>
18
19 =item 2
20
21 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
22
23 =item 3
24
25 B<Basic CRUD>
26
27 =item 4
28
29 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
30
31 =item 5
32
33 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
34
35 =item 6
36
37 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
38
39 =item 7
40
41 L<Testing|Catalyst::Manual::Tutorial::Testing>
42
43 =item 8
44
45 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
46
47 =item 9
48
49 L<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
50
51 =back
52
53
54
55 =head1 DESCRIPTION
56
57 This part of the tutorial builds on the fairly primitive application created in Part 2 to add basic support for Create, Read, Update, and Delete (CRUD) of C<Book> objects.  Note that the 'list' function in Part 2 already implements the Read portion of Crud (although Read normally refers to reading a single object; you could implement full read functionality using the techniques introduced below).  This section will focus on the Create and Delete aspects of CRUD.  More advanced capabilities, including full Update functionality, will be addressed in Part 8.
58
59 B<TIP>: Note that all of the code for this part of the tutorial can be pulled from the Catalyst Subversion repository in one step with the following command:
60
61     svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
62     IMPORTANT: Does not work yet.  Will be completed for final version.
63
64
65
66 =head1 FORMLESS SUBMISSION
67
68 Our initial attempt at object creation will utilize the "URL arguments" feature of Catalyst (we will employ the more common form-based submission in the sections that follow).
69
70
71 =head2 Include a Create Action in the Books Controller
72
73 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
74
75     =head2 url_create
76     
77     Create a book with the supplied title, rating and author
78     
79     =cut
80     
81     sub url_create : Local {
82         # In addition to self & context, get the title, rating & author_id args
83         # from the URL.  Note that Catalyst automatically puts extra information
84         # after the "/<controller_name>/<action_name/" into @_
85         my ($self, $c, $title, $rating, $author_id) = @_;
86     
87         # Call create() on the book model object. Pass the table 
88         # columns/field values we want to set as hash values
89         my $book = $c->model('MyAppDB::Book')->create({
90                 title   => $title,
91                 rating  => $rating
92             });
93         
94         # Add a record to the join table for this book, mapping to 
95         # appropriate author
96         $book->add_to_book_authors({author_id => $author_id});
97         # Note: Above is a shortcut for this:
98         # $book->create_related('book_authors', {author_id => $author_id});
99         
100         # Assign the Book object to the stash for display in the view
101         $c->stash->{book} = $book;
102     
103         # This is a hack to disable XSUB processing in Data::Dumper
104         # (it's used in the view).  This is a work-around for a bug in
105         # the interaction of some versions or Perl, Data::Dumper & DBIC.
106         # You won't need this if you aren't using Data::Dumper (or if
107         # you are running DBIC 0.06001 or greater), but adding it doesn't 
108         # hurt anything either.
109         $Data::Dumper::Useperl = 1;
110     
111         # Set the TT template to use
112         $c->stash->{template} = 'books/create_done.tt2';
113     }
114
115 Notice that Catalyst takes "extra slash-separated information" from the URL and passes it as arguments in C<@_>.  The C<url_create> action then uses a simple call to the DBIC C<create> method to add the requested information to the database (with a separate call to C<add_to_book_authors> to update the join table).  As do virtually all controller methods (at least the ones that directly handle user input), it then sets the template that should handle this request.
116
117
118 =head2 Include a Template for the C<url_create> Action:
119
120 Edit C<root/src/books/create_done.tt2> and then enter:
121
122     [% # Use the TT Dumper plugin to Data::Dumper variables to the browser   -%]
123     [% # Not a good idea for production use, though. :-)  'Indent=1' is      -%]
124     [% # optional, but prevents "massive indenting" of deeply nested objects -%]
125     [% USE Dumper(Indent=1) -%]
126     
127     [% # Set the page title -%]
128     [% META title = 'Book Created' %]
129     
130     [% # Output information about the record that was added.  Note use  -%]
131     [% # of 'first' to only list the first author (if > 1 author).      -%] 
132     <p>Added book '[% book.title %]' by '[% book.authors.first.last_name %]'
133     with a rating of [% book.rating %].</p>
134     
135     [% # Provide a link back to the list page                                    -%]
136     [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
137     <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
138     
139     [% # Try out the TT Dumper -%]
140     <pre>
141     Dump of the 'book' variable:
142     [% Dumper.dump(book) %]
143     </pre>
144
145 The TT C<USE> directive allows access to a variety of plugin modules (we are talking TT plugins here, not Catalyst plugins) to add extra functionality to the base TT capabilities.  Here, the plugin allows L<Data::Dumper|Data::Dumper> "pretty printing" of objects and variables.  Other than that, the rest of the code should be familiar from the examples in Part 2.
146
147 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view class created by TTSite redefines the name used to access the Catalyst context object in TT templates from the usual C<c> to C<Catalyst>.
148
149
150 =head2 Try the C<url_create> Feature
151
152 If the application is still running from before, use C<Ctrl-C> to kill it.  Then restart the server:
153
154     $ script/myapp_server.pl
155
156 Note that new path for C</books/url_create> appears in the startup debug output.
157
158 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development server auto-detect changed files and reload itself (if your browser acts odd, you should also try throwing in a C<-k>).  If you make changes to just the TT templates, you do not need to reload the development server (only changes to "compiled code" such as Controller and Model C<.pm> files require a reload).
159
160 Next, use your browser to enter the following URL:
161
162     http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
163
164 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by 'Stevens' with a rating of 5." along with a dump of the new book model object.  You should also see the following DBIC debug messages displayed in the development server log messages:
165
166     INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
167     INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
168
169 If you then click the "Return to list" link, you should find that there are now six books shown (if necessary, Shift-Reload your browser at the C</books/list> page).
170
171
172
173 =head1 MANUALLY BUILDING A CREATE FORM
174
175 Although the C<url_create> action in the previous step does begin to reveal the power and flexibility of both Catalyst and DBIC, it's obviously not a very realistic example of how users should be expected to enter data.  This section begins to address that concern.
176
177
178 =head2 Add Method to Display The Form
179
180 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
181
182     =head2 form_create
183     
184     Display form to collect information for book to create
185     
186     =cut
187     
188     sub form_create : Local {
189         my ($self, $c) = @_;
190     
191         # Set the TT template to use
192         $c->stash->{template} = 'books/form_create.tt2';
193     }
194
195 This action merely invokes a view containing a book creation form.
196
197
198 =head2 Add a Template for the Form
199
200 Open C<root/src/books/form_create.tt2> in your editor and enter:
201
202     [% META title = 'Book Create' -%]
203     
204     <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
205     <table>
206       <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
207       <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
208       <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
209     </table>
210     <input type="submit" name="Submit" value="Submit">
211     </form>
212
213 Note that we have specified the target of the form data as C<form_create_do>, the method created in the section that follows.
214
215
216 =head2 Add Method to Process Form Values and Update Database
217
218 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to save the form information to the databse:
219
220     =head2 form_create_do
221     
222     Take information from form and add to database
223     
224     =cut
225     
226     sub form_create_do : Local {
227         my ($self, $c) = @_;
228     
229         # Retrieve the values from the form
230         my $title     = $c->request->params->{title}     || 'N/A';
231         my $rating    = $c->request->params->{rating}    || 'N/A';
232         my $author_id = $c->request->params->{author_id} || '1';
233     
234         # Create the book
235         my $book = $c->model('MyAppDB::Book')->create({
236                 title   => $title,
237                 rating  => $rating,
238             });
239         # Handle relationship with author
240         $book->add_to_book_authors({author_id => $author_id});
241     
242         # Store new model object in stash
243         $c->stash->{book} = $book;
244     
245         # Avoid Data::Dumper issue mention earlier
246         # You can probably omit this    
247         $Data::Dumper::Useperl = 1;
248     
249         # Set the TT template to use
250         $c->stash->{template} = 'books/create_done.tt2';
251     }
252
253
254 =head2 Test Out The Form
255
256 If the application is still running from before, use C<Ctrl-C> to kill it.  Then restart the server:
257
258     $ script/myapp_server.pl
259
260 Point your browser to L<http://localhost:3000/books/form_create> and enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an author ID of 4.  You should then be forwarded to the same C<create_done.tt2> template seen in earlier examples.  Finally, click "Return to list" to view the full list of books.
261
262 B<Note:> Having the user enter the primary key ID for the author is obviously a bit crude; we will address this concern with a drop-down list in Part 8.
263
264
265
266 =head1 A SIMPLE DELETE FEATURE
267
268 Turning out attention to the delete portion of CRUD, this section illustrates some basic techniques that can be used to remove information from the database.
269
270
271 =head2 Include a Delete Link in the List
272
273 Edit C<root/src/books/list.tt2> and update it to the following (two sections have changed: 1) the additional '<th>Links</th>' table header, and 2) the four lines for the Delete link near the bottom).
274
275     [% # This is a TT comment.  The '-' at the end "chomps" the newline.  You won't -%]
276     [% # see this "chomping" in your browser because HTML ignores blank lines, but  -%]
277     [% # it WILL eliminate a blank line if you view the HTML source.  It's purely   -%]
278     [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
279     
280     [% # Provide a title to root/lib/site/header -%]
281     [% META title = 'Book List' -%]
282     
283     <table>
284     <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
285     [% # Display each book in a table row %]
286     [% FOREACH book IN books -%]
287       <tr>
288         <td>[% book.title %]</td>
289         <td>[% book.rating %]</td>
290         <td>
291           [% # Print author count in parens. 'book.authors' uses the 'many_to_many' -%]
292           [% # relationship to retrieve all of the authors of a book. 'size' is a   -%]
293           [% # TT VMethod to get the number of elements in a list.                  -%]
294           ([% book.authors.size %])
295           [% # Use an alternate form of a FOREACH loop to display authors.          -%]
296           [% # _ below is the TT string concatenation operator.                     -%]
297           [% author.last_name _' ' FOREACH author = book.authors %]
298           [% # Note: if many_to_many relationship not used in Authors.pm, you could -%]
299           [% # have used the following to 'walk' through the 'join table objects'   -%]
300           [% # bk_author.author.last_name _' ' FOREACH bk_author = book.book_authors %]
301         </td>
302         <td>
303           [% # Add a link to delete a book %]
304           <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
305         </td>
306       </tr>
307     [% END -%]
308     </table>
309
310 The additional code is obviously designed to add a new column to the right side of the table with a C<Delete> "button" (for simplicity, links will be used instead of full HTML buttons).
311
312
313 =head2 Add a Delete Action to the Controller
314
315 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the following method:
316
317     =head2 Delete 
318     
319     Delete a book
320         
321     =cut
322     
323     sub delete : Local {
324         # $id = primary key of book to delete
325         my ($self, $c, $id) = @_;
326     
327         # Search for the book and then delete it
328         $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
329     
330         # Set a status message to be displayed at the top of the view
331         $c->stash->{status_msg} = "Book deleted.";
332     
333         # Forward to the list action/method in this controller
334         $c->forward('list');
335     }
336
337 This method first deletes the book with the specified primary key ID.  However, it also removes the corresponding entry from the C<book_authors> table.  Note that C<delete_all> was used instead of C<delete>: whereas C<delete_all> also removes the join table entries in C<book_authors>, C<delete> does not.
338
339 Then, rather than forwarding to a "delete done" page as we did with the earlier create example, it simply sets the C<status_msg> to display a notification to the user as the normal list view is rendered.  
340
341 The C<delete> action uses the context C<forward> method to return the user to the book list.  The C<detach> method could have also been used.  Whereas C<forward> I<returns> to the original action once it is completed, C<detach> does I<not> return.  Other than that, the two are equivalent.
342
343 Another alternative to C<forward> would be to use C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>.  The C<forward> and C<redirect> operations differ in several important respects that stem from the fact that redirects cause the client browser to issue an entirely new HTTP request.  In doing so, this results in a new URL showing in the browser window.  And, because the stash information is reset for every request, the "Book deleted" message would not be displayed.
344
345
346 =head2 Try the Delete Feature
347
348 If the application is still running from before, use C<Ctrl-C> to kill it.  Then restart the server:
349
350     $ script/myapp_server.pl
351
352 Then point your browser to L<http://localhost:3000/books/list> and click the "Delete" link next to "TCPIP_Illustrated_Vol-2".  A green "Book deleted" status message should display at the top of the page, along with a list of the six remaining books.
353
354
355
356 =head1 AUTHOR
357
358 Kennedy Clark, C<hkclark@gmail.com>
359
360 Please report any errors, issues or suggestions to the author.
361
362 Copyright 2006, Kennedy Clark. All rights reserved.
363
364 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
365
366 Version: .94
367