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