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 You can checkout the source code for this example from the catalyst
67 subversion repository as per the instructions in
68 L<Catalyst::Manual::Tutorial::Intro>
70 =head1 FORMLESS SUBMISSION
72 Our initial attempt at object creation will utilize the "URL arguments"
73 feature of Catalyst (we will employ the more common form-based
74 submission in the sections that follow).
77 =head2 Include a Create Action in the Books Controller
79 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
83 Create a book with the supplied title, rating, and author
87 sub url_create : Local {
88 # In addition to self & context, get the title, rating, &
89 # author_id args from the URL. Note that Catalyst automatically
90 # puts extra information after the "/<controller_name>/<action_name/"
92 my ($self, $c, $title, $rating, $author_id) = @_;
94 # Call create() on the book model object. Pass the table
95 # columns/field values we want to set as hash values
96 my $book = $c->model('MyAppDB::Book')->create({
101 # Add a record to the join table for this book, mapping to
103 $book->add_to_book_authors({author_id => $author_id});
104 # Note: Above is a shortcut for this:
105 # $book->create_related('book_authors', {author_id => $author_id});
107 # Assign the Book object to the stash for display in the view
108 $c->stash->{book} = $book;
110 # This is a hack to disable XSUB processing in Data::Dumper
111 # (it's used in the view). This is a work-around for a bug in
112 # the interaction of some versions or Perl, Data::Dumper & DBIC.
113 # You won't need this if you aren't using Data::Dumper (or if
114 # you are running DBIC 0.06001 or greater), but adding it doesn't
115 # hurt anything either.
116 $Data::Dumper::Useperl = 1;
118 # Set the TT template to use
119 $c->stash->{template} = 'books/create_done.tt2';
122 Notice that Catalyst takes "extra slash-separated information" from the
123 URL and passes it as arguments in C<@_>. The C<url_create> action then
124 uses a simple call to the DBIC C<create> method to add the requested
125 information to the database (with a separate call to
126 C<add_to_book_authors> to update the join table). As do virtually all
127 controller methods (at least the ones that directly handle user input),
128 it then sets the template that should handle this request.
131 =head2 Include a Template for the C<url_create> Action:
133 Edit C<root/src/books/create_done.tt2> and then enter:
135 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
136 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
137 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
138 [% USE Dumper(Indent=1) -%]
140 [% # Set the page title. META can 'go back' and set values in templates -%]
141 [% # that have been processed 'before' this template (here it's for -%]
142 [% # root/lib/site/html and root/lib/site/header). Note that META on -%]
143 [% # simple strings (e.g., no variable interpolation). -%]
144 [% META title = 'Book Created' %]
146 [% # Output information about the record that was added. First title. -%]
147 <p>Added book '[% book.title %]'
149 [% # Output the last name of the first author. This is complicated by an -%]
150 [% # issue in TT 2.15 where blessed hash objects are not handled right. -%]
151 [% # First, fetch 'book.authors' from the DB once. -%]
152 [% authors = book.authors %]
153 [% # Now use IF statements to test if 'authors.first' is "working". If so, -%]
154 [% # we use it. Otherwise we use a hack that seems to keep TT 2.15 happy. -%]
155 by '[% authors.first.last_name IF authors.first;
156 authors.list.first.value.last_name IF ! authors.first %]'
158 [% # Output the rating for the book that was added -%]
159 with a rating of [% book.rating %].</p>
161 [% # Provide a link back to the list page -%]
162 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
163 <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
165 [% # Try out the TT Dumper (for development only!) -%]
167 Dump of the 'book' variable:
168 [% Dumper.dump(book) %]
171 The TT C<USE> directive allows access to a variety of plugin modules (TT
172 plugins, that is, not Catalyst plugins) to add extra functionality to
173 the base TT capabilities. Here, the plugin allows L<Data::Dumper>
174 "pretty printing" of objects and variables. Other than that, the rest
175 of the code should be familiar from the examples in Part 2.
177 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
178 class created by TTSite redefines the name used to access the Catalyst
179 context object in TT templates from the usual C<c> to C<Catalyst>.
181 =head2 Try the C<url_create> Feature
183 If the application is still running from before, use C<Ctrl-C> to kill
184 it. Then restart the server:
186 $ script/myapp_server.pl
188 Note that new path for C</books/url_create> appears in the startup debug
191 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
192 server auto-detect changed files and reload itself (if your browser acts
193 odd, you should also try throwing in a C<-k>). If you make changes to
194 the TT templates only, you do not need to reload the development server
195 (only changes to "compiled code" such as Controller and Model C<.pm>
196 files require a reload).
198 Next, use your browser to enter the following URL:
200 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
202 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by
203 'Stevens' with a rating of 5." along with a dump of the new book model
204 object. You should also see the following DBIC debug messages displayed
205 in the development server log messages:
207 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
208 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
210 If you then click the "Return to list" link, you should find that there
211 are now six books shown (if necessary, Shift-Reload your browser at the
212 C</books/list> page).
215 =head1 MANUALLY BUILDING A CREATE FORM
217 Although the C<url_create> action in the previous step does begin to
218 reveal the power and flexibility of both Catalyst and DBIC, it's
219 obviously not a very realistic example of how users should be expected
220 to enter data. This section begins to address that concern.
223 =head2 Add Method to Display The Form
225 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
229 Display form to collect information for book to create
233 sub form_create : Local {
236 # Set the TT template to use
237 $c->stash->{template} = 'books/form_create.tt2';
240 This action simply invokes a view containing a book creation form.
242 =head2 Add a Template for the Form
244 Open C<root/src/books/form_create.tt2> in your editor and enter:
246 [% META title = 'Manual Form Book Create' -%]
248 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
250 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
251 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
252 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
254 <input type="submit" name="Submit" value="Submit">
257 Note that we have specified the target of the form data as
258 C<form_create_do>, the method created in the section that follows.
260 =head2 Add Method to Process Form Values and Update Database
262 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
263 save the form information to the database:
265 =head2 form_create_do
267 Take information from form and add to database
271 sub form_create_do : Local {
274 # Retrieve the values from the form
275 my $title = $c->request->params->{title} || 'N/A';
276 my $rating = $c->request->params->{rating} || 'N/A';
277 my $author_id = $c->request->params->{author_id} || '1';
280 my $book = $c->model('MyAppDB::Book')->create({
284 # Handle relationship with author
285 $book->add_to_book_authors({author_id => $author_id});
287 # Store new model object in stash
288 $c->stash->{book} = $book;
290 # Avoid Data::Dumper issue mentioned earlier
291 # You can probably omit this
292 $Data::Dumper::Useperl = 1;
294 # Set the TT template to use
295 $c->stash->{template} = 'books/create_done.tt2';
299 =head2 Test Out The Form
301 If the application is still running from before, use C<Ctrl-C> to kill
302 it. Then restart the server:
304 $ script/myapp_server.pl
306 Point your browser to L<http://localhost:3000/books/form_create> and
307 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
308 author ID of 4. You should then be forwarded to the same
309 C<create_done.tt2> template seen in earlier examples. Finally, click
310 "Return to list" to view the full list of books.
312 B<Note:> Having the user enter the primary key ID for the author is
313 obviously crude; we will address this concern with a drop-down list in
316 =head1 A SIMPLE DELETE FEATURE
318 Turning our attention to the delete portion of CRUD, this section
319 illustrates some basic techniques that can be used to remove information
323 =head2 Include a Delete Link in the List
325 Edit C<root/src/books/list.tt2> and update it to the following (two
326 sections have changed: 1) the additional '<th>Links</th>' table header,
327 and 2) the four lines for the Delete link near the bottom).
329 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
330 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
331 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
332 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
334 [% # Provide a title to root/lib/site/header -%]
335 [% META title = 'Book List' -%]
338 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
339 [% # Display each book in a table row %]
340 [% FOREACH book IN books -%]
342 <td>[% book.title %]</td>
343 <td>[% book.rating %]</td>
345 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
346 [% # loop in 'side effect notation' to load just the last names of the -%]
347 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
348 [% # a value, so nothing will be printed here. But, if you have something -%]
349 [% # in TT that does return a method and you don't want it printed, you -%]
350 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
351 [% # call it and discard the return value. -%]
353 tt_authors.push(author.last_name) FOREACH author = book.authors %]
354 [% # Now use a TT 'virtual method' to display the author count -%]
355 ([% tt_authors.size %])
356 [% # Use another TT vmethod to join & print the names & comma separators -%]
357 [% tt_authors.join(', ') %]
360 [% # Add a link to delete a book %]
361 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
367 The additional code is obviously designed to add a new column to the
368 right side of the table with a C<Delete> "button" (for simplicity, links
369 will be used instead of full HTML buttons).
371 =head2 Add a Delete Action to the Controller
373 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
383 # $id = primary key of book to delete
384 my ($self, $c, $id) = @_;
386 # Search for the book and then delete it
387 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
389 # Set a status message to be displayed at the top of the view
390 $c->stash->{status_msg} = "Book deleted.";
392 # Forward to the list action/method in this controller
396 This method first deletes the book with the specified primary key ID.
397 However, it also removes the corresponding entry from the
398 C<book_authors> table. Note that C<delete_all> was used instead of
399 C<delete>: whereas C<delete_all> also removes the join table entries in
400 C<book_authors>, C<delete> does not.
402 Then, rather than forwarding to a "delete done" page as we did with the
403 earlier create example, it simply sets the C<status_msg> to display a
404 notification to the user as the normal list view is rendered.
406 The C<delete> action uses the context C<forward> method to return the
407 user to the book list. The C<detach> method could have also been used.
408 Whereas C<forward> I<returns> to the original action once it is
409 completed, C<detach> does I<not> return. Other than that, the two are
412 Another alternative to C<forward> would be to use
413 C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The
414 C<forward> and C<redirect> operations differ in several important
415 respects that stem from the fact that redirects cause the client browser
416 to issue an entirely new HTTP request. In doing so, this results in a
417 new URL showing in the browser window. And, because the stash
418 information is reset for every request, the "Book deleted" message would
422 =head2 Try the Delete Feature
424 If the application is still running from before, use C<Ctrl-C> to kill
425 it. Then restart the server:
427 $ script/myapp_server.pl
429 Then point your browser to L<http://localhost:3000/books/list> and click
430 the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book
431 deleted" status message should display at the top of the page, along
432 with a list of the six remaining books.
437 Kennedy Clark, C<hkclark@gmail.com>
439 Please report any errors, issues or suggestions to the author. The
440 most recent version of the Catalyst Tutorial can be found at
441 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
443 Copyright 2006, Kennedy Clark, under Creative Commons License
444 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).