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<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
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 checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
71 IMPORTANT: Does not work yet. Will be completed for final version.
74 =head1 FORMLESS SUBMISSION
76 Our initial attempt at object creation will utilize the "URL arguments"
77 feature of Catalyst (we will employ the more common form-based
78 submission in the sections that follow).
81 =head2 Include a Create Action in the Books Controller
83 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
87 Create a book with the supplied title, rating, and author
91 sub url_create : Local {
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/"
96 my ($self, $c, $title, $rating, $author_id) = @_;
98 # Call create() on the book model object. Pass the table
99 # columns/field values we want to set as hash values
100 my $book = $c->model('MyAppDB::Book')->create({
105 # Add a record to the join table for this book, mapping to
107 $book->add_to_book_authors({author_id => $author_id});
108 # Note: Above is a shortcut for this:
109 # $book->create_related('book_authors', {author_id => $author_id});
111 # Assign the Book object to the stash for display in the view
112 $c->stash->{book} = $book;
114 # This is a hack to disable XSUB processing in Data::Dumper
115 # (it's used in the view). This is a work-around for a bug in
116 # the interaction of some versions or Perl, Data::Dumper & DBIC.
117 # You won't need this if you aren't using Data::Dumper (or if
118 # you are running DBIC 0.06001 or greater), but adding it doesn't
119 # hurt anything either.
120 $Data::Dumper::Useperl = 1;
122 # Set the TT template to use
123 $c->stash->{template} = 'books/create_done.tt2';
126 Notice that Catalyst takes "extra slash-separated information" from the
127 URL and passes it as arguments in C<@_>. The C<url_create> action then
128 uses a simple call to the DBIC C<create> method to add the requested
129 information to the database (with a separate call to
130 C<add_to_book_authors> to update the join table). As do virtually all
131 controller methods (at least the ones that directly handle user input),
132 it then sets the template that should handle this request.
135 =head2 Include a Template for the C<url_create> Action:
137 Edit C<root/src/books/create_done.tt2> and then enter:
139 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
140 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
141 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
142 [% USE Dumper(Indent=1) -%]
144 [% # Set the page title. META can 'go back' and set values in templates -%]
145 [% # that have been processed 'before' this template (here it's for -%]
146 [% # root/lib/site/html and root/lib/site/header). Note that META on -%]
147 [% # simple strings (e.g., no variable interpolation). -%]
148 [% META title = 'Book Created' %]
150 [% # Output information about the record that was added. Note use -%]
151 [% # of 'first' to only list the first author (if > 1 author). -%]
152 <p>Added book '[% book.title %]' by '[% book.authors.first.last_name %]'
153 with a rating of [% book.rating %].</p>
155 [% # Provide a link back to the list page -%]
156 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
157 <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
159 [% # Try out the TT Dumper (for development only!) -%]
161 Dump of the 'book' variable:
162 [% Dumper.dump(book) %]
165 The TT C<USE> directive allows access to a variety of plugin modules (TT
166 plugins, that is, not Catalyst plugins) to add extra functionality to
167 the base TT capabilities. Here, the plugin allows L<Data::Dumper>
168 "pretty printing" of objects and variables. Other than that, the rest
169 of the code should be familiar from the examples in Part 2.
171 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
172 class created by TTSite redefines the name used to access the Catalyst
173 context object in TT templates from the usual C<c> to C<Catalyst>.
175 =head2 Try the C<url_create> Feature
177 If the application is still running from before, use C<Ctrl-C> to kill
178 it. Then restart the server:
180 $ script/myapp_server.pl
182 Note that new path for C</books/url_create> appears in the startup debug
185 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
186 server auto-detect changed files and reload itself (if your browser acts
187 odd, you should also try throwing in a C<-k>). If you make changes to
188 the TT templates only, you do not need to reload the development server
189 (only changes to "compiled code" such as Controller and Model C<.pm>
190 files require a reload).
192 Next, use your browser to enter the following URL:
194 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
196 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by
197 'Stevens' with a rating of 5." along with a dump of the new book model
198 object. You should also see the following DBIC debug messages displayed
199 in the development server log messages:
201 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
202 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
204 If you then click the "Return to list" link, you should find that there
205 are now six books shown (if necessary, Shift-Reload your browser at the
206 C</books/list> page).
209 =head1 MANUALLY BUILDING A CREATE FORM
211 Although the C<url_create> action in the previous step does begin to
212 reveal the power and flexibility of both Catalyst and DBIC, it's
213 obviously not a very realistic example of how users should be expected
214 to enter data. This section begins to address that concern.
217 =head2 Add Method to Display The Form
219 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
223 Display form to collect information for book to create
227 sub form_create : Local {
230 # Set the TT template to use
231 $c->stash->{template} = 'books/form_create.tt2';
234 This action simply invokes a view containing a book creation form.
236 =head2 Add a Template for the Form
238 Open C<root/src/books/form_create.tt2> in your editor and enter:
240 [% META title = 'Manual Form Book Create' -%]
242 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
244 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
245 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
246 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
248 <input type="submit" name="Submit" value="Submit">
251 Note that we have specified the target of the form data as
252 C<form_create_do>, the method created in the section that follows.
254 =head2 Add Method to Process Form Values and Update Database
256 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
257 save the form information to the databse:
259 =head2 form_create_do
261 Take information from form and add to database
265 sub form_create_do : Local {
268 # Retrieve the values from the form
269 my $title = $c->request->params->{title} || 'N/A';
270 my $rating = $c->request->params->{rating} || 'N/A';
271 my $author_id = $c->request->params->{author_id} || '1';
274 my $book = $c->model('MyAppDB::Book')->create({
278 # Handle relationship with author
279 $book->add_to_book_authors({author_id => $author_id});
281 # Store new model object in stash
282 $c->stash->{book} = $book;
284 # Avoid Data::Dumper issue mentioned earlier
285 # You can probably omit this
286 $Data::Dumper::Useperl = 1;
288 # Set the TT template to use
289 $c->stash->{template} = 'books/create_done.tt2';
293 =head2 Test Out The Form
295 If the application is still running from before, use C<Ctrl-C> to kill
296 it. Then restart the server:
298 $ script/myapp_server.pl
300 Point your browser to L<http://localhost:3000/books/form_create> and
301 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
302 author ID of 4. You should then be forwarded to the same
303 C<create_done.tt2> template seen in earlier examples. Finally, click
304 "Return to list" to view the full list of books.
306 B<Note:> Having the user enter the primary key ID for the author is
307 obviously crude; we will address this concern with a drop-down list in
310 =head1 A SIMPLE DELETE FEATURE
312 Turning out attention to the delete portion of CRUD, this section
313 illustrates some basic techniques that can be used to remove information
317 =head2 Include a Delete Link in the List
319 Edit C<root/src/books/list.tt2> and update it to the following (two
320 sections have changed: 1) the additional '<th>Links</th>' table header,
321 and 2) the four lines for the Delete link near the bottom).
323 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
324 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
325 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
326 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
328 [% # Provide a title to root/lib/site/header -%]
329 [% META title = 'Book List' -%]
332 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
333 [% # Display each book in a table row %]
334 [% FOREACH book IN books -%]
336 <td>[% book.title %]</td>
337 <td>[% book.rating %]</td>
339 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
340 [% # loop in 'side effect notation' to load just the last names of the -%]
341 [% # authors into the list. Note that we are making a bogus assignment to -%]
342 [% # the 'xx' vbl to avoid printing the size of the list after each push. -%]
344 xx = tt_authors.push(author.last_name) FOREACH author = book.authors %]
345 [% # Now use a TT 'virtual method' to display the author count -%]
346 ([% tt_authors.size %])
347 [% # Use another TT virtual method to join the names with comma separators -%]
348 [% tt_authors.join(', ') %]
351 [% # Add a link to delete a book %]
352 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
358 The additional code is obviously designed to add a new column to the
359 right side of the table with a C<Delete> "button" (for simplicity, links
360 will be used instead of full HTML buttons).
362 =head2 Add a Delete Action to the Controller
364 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
374 # $id = primary key of book to delete
375 my ($self, $c, $id) = @_;
377 # Search for the book and then delete it
378 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
380 # Set a status message to be displayed at the top of the view
381 $c->stash->{status_msg} = "Book deleted.";
383 # Forward to the list action/method in this controller
387 This method first deletes the book with the specified primary key ID.
388 However, it also removes the corresponding entry from the
389 C<book_authors> table. Note that C<delete_all> was used instead of
390 C<delete>: whereas C<delete_all> also removes the join table entries in
391 C<book_authors>, C<delete> does not.
393 Then, rather than forwarding to a "delete done" page as we did with the
394 earlier create example, it simply sets the C<status_msg> to display a
395 notification to the user as the normal list view is rendered.
397 The C<delete> action uses the context C<forward> method to return the
398 user to the book list. The C<detach> method could have also been used.
399 Whereas C<forward> I<returns> to the original action once it is
400 completed, C<detach> does I<not> return. Other than that, the two are
403 Another alternative to C<forward> would be to use
404 C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The
405 C<forward> and C<redirect> operations differ in several important
406 respects that stem from the fact that redirects cause the client browser
407 to issue an entirely new HTTP request. In doing so, this results in a
408 new URL showing in the browser window. And, because the stash
409 information is reset for every request, the "Book deleted" message would
413 =head2 Try the Delete Feature
415 If the application is still running from before, use C<Ctrl-C> to kill
416 it. Then restart the server:
418 $ script/myapp_server.pl
420 Then point your browser to L<http://localhost:3000/books/list> and click
421 the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book
422 deleted" status message should display at the top of the page, along
423 with a list of the six remaining books.
427 Kennedy Clark, C<hkclark@gmail.com>
429 Please report any errors, issues or suggestions to the author.
431 Copyright 2006, Kennedy Clark, under Creative Commons License
432 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).