3 Catalyst::Manual::Tutorial::BasicCRUD - Catalyst Tutorial - Part 3: Basic CRUD
8 This is B<Part 3 of 9> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
28 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
32 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
36 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
40 L<Testing|Catalyst::Manual::Tutorial::Testing>
44 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
48 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
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
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
70 svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/5.7X/BasicCRUD MyApp
73 =head1 FORMLESS SUBMISSION
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).
80 =head2 Include a Create Action in the Books Controller
82 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
86 Create a book with the supplied title, rating, and author
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/"
95 my ($self, $c, $title, $rating, $author_id) = @_;
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({
104 # Add a record to the join table for this book, mapping to
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});
110 # Assign the Book object to the stash for display in the view
111 $c->stash->{book} = $book;
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;
121 # Set the TT template to use
122 $c->stash->{template} = 'books/create_done.tt2';
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.
134 =head2 Include a Template for the C<url_create> Action:
136 Edit C<root/src/books/create_done.tt2> and then enter:
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) -%]
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' %]
149 [% # Output information about the record that was added. First title. -%]
150 <p>Added book '[% book.title %]'
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 %]'
161 [% # Output the rating for the book that was added -%]
162 with a rating of [% book.rating %].</p>
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>
168 [% # Try out the TT Dumper (for development only!) -%]
170 Dump of the 'book' variable:
171 [% Dumper.dump(book) %]
174 The TT C<USE> directive allows access to a variety of plugin modules (TT
175 plugins, that is, not Catalyst plugins) to add extra functionality to
176 the base TT capabilities. Here, the plugin allows L<Data::Dumper>
177 "pretty printing" of objects and variables. Other than that, the rest
178 of the code should be familiar from the examples in Part 2.
180 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
181 class created by TTSite redefines the name used to access the Catalyst
182 context object in TT templates from the usual C<c> to C<Catalyst>.
184 =head2 Try the C<url_create> Feature
186 If the application is still running from before, use C<Ctrl-C> to kill
187 it. Then restart the server:
189 $ script/myapp_server.pl
191 Note that new path for C</books/url_create> appears in the startup debug
194 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
195 server auto-detect changed files and reload itself (if your browser acts
196 odd, you should also try throwing in a C<-k>). If you make changes to
197 the TT templates only, you do not need to reload the development server
198 (only changes to "compiled code" such as Controller and Model C<.pm>
199 files require a reload).
201 Next, use your browser to enter the following URL:
203 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
205 Your 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
207 object. You should also see the following DBIC debug messages displayed
208 in the development server log messages:
210 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
211 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
213 If you then click the "Return to list" link, you should find that there
214 are now six books shown (if necessary, Shift-Reload your browser at the
215 C</books/list> page).
218 =head1 MANUALLY BUILDING A CREATE FORM
220 Although the C<url_create> action in the previous step does begin to
221 reveal the power and flexibility of both Catalyst and DBIC, it's
222 obviously not a very realistic example of how users should be expected
223 to enter data. This section begins to address that concern.
226 =head2 Add Method to Display The Form
228 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
232 Display form to collect information for book to create
236 sub form_create : Local {
239 # Set the TT template to use
240 $c->stash->{template} = 'books/form_create.tt2';
243 This action simply invokes a view containing a book creation form.
245 =head2 Add a Template for the Form
247 Open C<root/src/books/form_create.tt2> in your editor and enter:
249 [% META title = 'Manual Form Book Create' -%]
251 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
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>
257 <input type="submit" name="Submit" value="Submit">
260 Note that we have specified the target of the form data as
261 C<form_create_do>, the method created in the section that follows.
263 =head2 Add Method to Process Form Values and Update Database
265 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
266 save the form information to the database:
268 =head2 form_create_do
270 Take information from form and add to database
274 sub form_create_do : Local {
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';
283 my $book = $c->model('MyAppDB::Book')->create({
287 # Handle relationship with author
288 $book->add_to_book_authors({author_id => $author_id});
290 # Store new model object in stash
291 $c->stash->{book} = $book;
293 # Avoid Data::Dumper issue mentioned earlier
294 # You can probably omit this
295 $Data::Dumper::Useperl = 1;
297 # Set the TT template to use
298 $c->stash->{template} = 'books/create_done.tt2';
302 =head2 Test Out The Form
304 If the application is still running from before, use C<Ctrl-C> to kill
305 it. Then restart the server:
307 $ script/myapp_server.pl
309 Point your browser to L<http://localhost:3000/books/form_create> and
310 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
311 author ID of 4. You should then be forwarded to the same
312 C<create_done.tt2> template seen in earlier examples. Finally, click
313 "Return to list" to view the full list of books.
315 B<Note:> Having the user enter the primary key ID for the author is
316 obviously crude; we will address this concern with a drop-down list in
319 =head1 A SIMPLE DELETE FEATURE
321 Turning our attention to the delete portion of CRUD, this section
322 illustrates some basic techniques that can be used to remove information
326 =head2 Include a Delete Link in the List
328 Edit C<root/src/books/list.tt2> and update it to the following (two
329 sections have changed: 1) the additional '<th>Links</th>' table header,
330 and 2) the four lines for the Delete link near the bottom).
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. -%]
337 [% # Provide a title to root/lib/site/header -%]
338 [% META title = 'Book List' -%]
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 -%]
345 <td>[% book.title %]</td>
346 <td>[% book.rating %]</td>
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 -%]
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. -%]
356 tt_authors.push(author.last_name) FOREACH author = book.authors %]
357 [% # Now use a TT 'virtual method' to display the author count -%]
358 ([% tt_authors.size %])
359 [% # Use another TT vmethod to join & print the names & comma separators -%]
360 [% tt_authors.join(', ') %]
363 [% # Add a link to delete a book %]
364 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
370 The additional code is obviously designed to add a new column to the
371 right side of the table with a C<Delete> "button" (for simplicity, links
372 will be used instead of full HTML buttons).
374 =head2 Add a Delete Action to the Controller
376 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
386 # $id = primary key of book to delete
387 my ($self, $c, $id) = @_;
389 # Search for the book and then delete it
390 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
392 # Set a status message to be displayed at the top of the view
393 $c->stash->{status_msg} = "Book deleted.";
395 # Forward to the list action/method in this controller
399 This method first deletes the book with the specified primary key ID.
400 However, it also removes the corresponding entry from the
401 C<book_authors> table. Note that C<delete_all> was used instead of
402 C<delete>: whereas C<delete_all> also removes the join table entries in
403 C<book_authors>, C<delete> does not.
405 Then, rather than forwarding to a "delete done" page as we did with the
406 earlier create example, it simply sets the C<status_msg> to display a
407 notification to the user as the normal list view is rendered.
409 The C<delete> action uses the context C<forward> method to return the
410 user to the book list. The C<detach> method could have also been used.
411 Whereas C<forward> I<returns> to the original action once it is
412 completed, C<detach> does I<not> return. Other than that, the two are
415 Another alternative to C<forward> would be to use
416 C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The
417 C<forward> and C<redirect> operations differ in several important
418 respects that stem from the fact that redirects cause the client browser
419 to issue an entirely new HTTP request. In doing so, this results in a
420 new URL showing in the browser window. And, because the stash
421 information is reset for every request, the "Book deleted" message would
425 =head2 Try the Delete Feature
427 If the application is still running from before, use C<Ctrl-C> to kill
428 it. Then restart the server:
430 $ script/myapp_server.pl
432 Then point your browser to L<http://localhost:3000/books/list> and click
433 the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book
434 deleted" status message should display at the top of the page, along
435 with a list of the six remaining books.
440 Kennedy Clark, C<hkclark@gmail.com>
442 Please report any errors, issues or suggestions to the author. The
443 most recent version of the Catalyst Tutorial can be found at
444 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
446 Copyright 2006, Kennedy Clark, under Creative Commons License
447 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).