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