Remove comment about code not being in subversion yet.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / BasicCRUD.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD
4d583dd8 4
5
6=head1 OVERVIEW
7
8This is B<Part 3 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
24B<Basic CRUD>
25
26=item 4
27
28L<Authentication|Catalyst::Manual::Tutorial::Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
44L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
45
46=item 9
47
48L<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
49
50=back
51
52
53
54=head1 DESCRIPTION
55
64ccd8a8 56This part of the tutorial builds on the fairly primitive application
57created in Part 2 to add basic support for Create, Read, Update, and
58Delete (CRUD) of C<Book> objects. Note that the 'list' function in Part
71dedf57 592 already implements the Read portion of CRUD (although Read normally
64ccd8a8 60refers to reading a single object; you could implement full read
61functionality using the techniques introduced below). This section will
62focus on the Create and Delete aspects of CRUD. More advanced
63capabilities, including full Update functionality, will be addressed in
64Part 8.
4d583dd8 65
64ccd8a8 66B<TIP>: Note that all of the code for this part of the tutorial can be
67pulled from the Catalyst Subversion repository in one step with the
68following command:
4d583dd8 69
d645910d 70 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@4611 .
4d583dd8 71
72
4d583dd8 73=head1 FORMLESS SUBMISSION
74
64ccd8a8 75Our initial attempt at object creation will utilize the "URL arguments"
76feature of Catalyst (we will employ the more common form-based
77submission in the sections that follow).
4d583dd8 78
79
80=head2 Include a Create Action in the Books Controller
81
82Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
83
84 =head2 url_create
85
71dedf57 86 Create a book with the supplied title, rating, and author
4d583dd8 87
88 =cut
89
90 sub url_create : Local {
71dedf57 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 @_
4d583dd8 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({
5c1f2a06 100 title => $title,
101 rating => $rating
4d583dd8 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
64ccd8a8 125Notice that Catalyst takes "extra slash-separated information" from the
126URL and passes it as arguments in C<@_>. The C<url_create> action then
127uses a simple call to the DBIC C<create> method to add the requested
128information to the database (with a separate call to
129C<add_to_book_authors> to update the join table). As do virtually all
130controller methods (at least the ones that directly handle user input),
131it then sets the template that should handle this request.
4d583dd8 132
133
134=head2 Include a Template for the C<url_create> Action:
135
136Edit 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
5c1f2a06 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). -%]
4d583dd8 147 [% META title = 'Book Created' %]
148
149 [% # Output information about the record that was added. Note use -%]
cc548726 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 %]'
4d583dd8 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
71dedf57 162 [% # Try out the TT Dumper (for development only!) -%]
4d583dd8 163 <pre>
164 Dump of the 'book' variable:
165 [% Dumper.dump(book) %]
166 </pre>
167
71dedf57 168The TT C<USE> directive allows access to a variety of plugin modules (TT
169plugins, that is, not Catalyst plugins) to add extra functionality to
170the base TT capabilities. Here, the plugin allows L<Data::Dumper>
171"pretty printing" of objects and variables. Other than that, the rest
172of the code should be familiar from the examples in Part 2.
4d583dd8 173
64ccd8a8 174B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
175class created by TTSite redefines the name used to access the Catalyst
176context object in TT templates from the usual C<c> to C<Catalyst>.
4d583dd8 177
4d583dd8 178=head2 Try the C<url_create> Feature
179
64ccd8a8 180If the application is still running from before, use C<Ctrl-C> to kill
71dedf57 181it. Then restart the server:
4d583dd8 182
183 $ script/myapp_server.pl
184
64ccd8a8 185Note that new path for C</books/url_create> appears in the startup debug
186output.
4d583dd8 187
64ccd8a8 188B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
189server auto-detect changed files and reload itself (if your browser acts
190odd, you should also try throwing in a C<-k>). If you make changes to
71dedf57 191the TT templates only, you do not need to reload the development server
64ccd8a8 192(only changes to "compiled code" such as Controller and Model C<.pm>
193files require a reload).
4d583dd8 194
195Next, use your browser to enter the following URL:
196
197 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
198
64ccd8a8 199Your 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
201object. You should also see the following DBIC debug messages displayed
202in the development server log messages:
4d583dd8 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
64ccd8a8 207If you then click the "Return to list" link, you should find that there
208are now six books shown (if necessary, Shift-Reload your browser at the
209C</books/list> page).
4d583dd8 210
211
4d583dd8 212=head1 MANUALLY BUILDING A CREATE FORM
213
64ccd8a8 214Although the C<url_create> action in the previous step does begin to
215reveal the power and flexibility of both Catalyst and DBIC, it's
216obviously not a very realistic example of how users should be expected
217to enter data. This section begins to address that concern.
4d583dd8 218
219
220=head2 Add Method to Display The Form
221
222Edit 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
71dedf57 237This action simply invokes a view containing a book creation form.
4d583dd8 238
239=head2 Add a Template for the Form
240
241Open C<root/src/books/form_create.tt2> in your editor and enter:
242
5c1f2a06 243 [% META title = 'Manual Form Book Create' -%]
4d583dd8 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
64ccd8a8 254Note that we have specified the target of the form data as
255C<form_create_do>, the method created in the section that follows.
4d583dd8 256
4d583dd8 257=head2 Add Method to Process Form Values and Update Database
258
64ccd8a8 259Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
260save the form information to the databse:
4d583dd8 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
71dedf57 287 # Avoid Data::Dumper issue mentioned earlier
4d583dd8 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
71dedf57 298If the application is still running from before, use C<Ctrl-C> to kill
299it. Then restart the server:
4d583dd8 300
301 $ script/myapp_server.pl
302
64ccd8a8 303Point your browser to L<http://localhost:3000/books/form_create> and
304enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
305author ID of 4. You should then be forwarded to the same
306C<create_done.tt2> template seen in earlier examples. Finally, click
307"Return to list" to view the full list of books.
4d583dd8 308
64ccd8a8 309B<Note:> Having the user enter the primary key ID for the author is
71dedf57 310obviously crude; we will address this concern with a drop-down list in
311Part 8.
4d583dd8 312
313=head1 A SIMPLE DELETE FEATURE
314
64ccd8a8 315Turning out attention to the delete portion of CRUD, this section
316illustrates some basic techniques that can be used to remove information
317from the database.
4d583dd8 318
319
320=head2 Include a Delete Link in the List
321
64ccd8a8 322Edit C<root/src/books/list.tt2> and update it to the following (two
323sections have changed: 1) the additional '<th>Links</th>' table header,
324and 2) the four lines for the Delete link near the bottom).
4d583dd8 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>
5c1f2a06 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(', ') %]
4d583dd8 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
64ccd8a8 361The additional code is obviously designed to add a new column to the
362right side of the table with a C<Delete> "button" (for simplicity, links
363will be used instead of full HTML buttons).
4d583dd8 364
4d583dd8 365=head2 Add a Delete Action to the Controller
366
64ccd8a8 367Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
368following method:
4d583dd8 369
cc548726 370 =head2 delete
4d583dd8 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
64ccd8a8 390This method first deletes the book with the specified primary key ID.
391However, it also removes the corresponding entry from the
392C<book_authors> table. Note that C<delete_all> was used instead of
393C<delete>: whereas C<delete_all> also removes the join table entries in
394C<book_authors>, C<delete> does not.
4d583dd8 395
64ccd8a8 396Then, rather than forwarding to a "delete done" page as we did with the
397earlier create example, it simply sets the C<status_msg> to display a
398notification to the user as the normal list view is rendered.
4d583dd8 399
64ccd8a8 400The C<delete> action uses the context C<forward> method to return the
401user to the book list. The C<detach> method could have also been used.
402Whereas C<forward> I<returns> to the original action once it is
403completed, C<detach> does I<not> return. Other than that, the two are
404equivalent.
4d583dd8 405
64ccd8a8 406Another alternative to C<forward> would be to use
407C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The
408C<forward> and C<redirect> operations differ in several important
409respects that stem from the fact that redirects cause the client browser
410to issue an entirely new HTTP request. In doing so, this results in a
411new URL showing in the browser window. And, because the stash
412information is reset for every request, the "Book deleted" message would
413not be displayed.
4d583dd8 414
415
416=head2 Try the Delete Feature
417
64ccd8a8 418If the application is still running from before, use C<Ctrl-C> to kill
419it. Then restart the server:
4d583dd8 420
421 $ script/myapp_server.pl
422
64ccd8a8 423Then point your browser to L<http://localhost:3000/books/list> and click
424the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book
425deleted" status message should display at the top of the page, along
426with a list of the six remaining books.
4d583dd8 427
a63e6e67 428
4d583dd8 429=head1 AUTHOR
430
431Kennedy Clark, C<hkclark@gmail.com>
432
eed93301 433Please report any errors, issues or suggestions to the author. The
434most recent version of the Catlayst Tutorial can be found at
435L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 436
64ccd8a8 437Copyright 2006, Kennedy Clark, under Creative Commons License
438(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
4d583dd8 439