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 -r 4611 .
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. Note use -%]
150 [% # of 'first' to only list the first author (if > 1 author). TT -%]
151 [% # v2.15 has an issue that requires -%]
152 [% # 'book.authors.list.first.value.last_name' vs. the shorter -%]
153 [% # 'book.authors.first.last_name' in prior versions. -%]
154 <p>Added book '[% book.title %]'
155 by '[% book.authors.list.first.value.last_name %]'
156 with a rating of [% book.rating %].</p>
158 [% # Provide a link back to the list page -%]
159 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
160 <p><a href="[% Catalyst.uri_for('/books/list') %]">Return to list</a></p>
162 [% # Try out the TT Dumper (for development only!) -%]
164 Dump of the 'book' variable:
165 [% Dumper.dump(book) %]
168 The TT C<USE> directive allows access to a variety of plugin modules (TT
169 plugins, that is, not Catalyst plugins) to add extra functionality to
170 the base TT capabilities. Here, the plugin allows L<Data::Dumper>
171 "pretty printing" of objects and variables. Other than that, the rest
172 of the code should be familiar from the examples in Part 2.
174 B<IMPORTANT NOTE> As mentioned earlier, the C<MyApp::View::TT.pm> view
175 class created by TTSite redefines the name used to access the Catalyst
176 context object in TT templates from the usual C<c> to C<Catalyst>.
178 =head2 Try the C<url_create> Feature
180 If the application is still running from before, use C<Ctrl-C> to kill
181 it. Then restart the server:
183 $ script/myapp_server.pl
185 Note that new path for C</books/url_create> appears in the startup debug
188 B<TIP>: You can use C<script/myapp_server.pl -r> to have the development
189 server auto-detect changed files and reload itself (if your browser acts
190 odd, you should also try throwing in a C<-k>). If you make changes to
191 the TT templates only, you do not need to reload the development server
192 (only changes to "compiled code" such as Controller and Model C<.pm>
193 files require a reload).
195 Next, use your browser to enter the following URL:
197 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
199 Your browser should display " Added book 'TCPIP_Illustrated_Vol-2' by
200 'Stevens' with a rating of 5." along with a dump of the new book model
201 object. You should also see the following DBIC debug messages displayed
202 in the development server log messages:
204 INSERT INTO books (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
205 INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): `4', `6'
207 If you then click the "Return to list" link, you should find that there
208 are now six books shown (if necessary, Shift-Reload your browser at the
209 C</books/list> page).
212 =head1 MANUALLY BUILDING A CREATE FORM
214 Although the C<url_create> action in the previous step does begin to
215 reveal the power and flexibility of both Catalyst and DBIC, it's
216 obviously not a very realistic example of how users should be expected
217 to enter data. This section begins to address that concern.
220 =head2 Add Method to Display The Form
222 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
226 Display form to collect information for book to create
230 sub form_create : Local {
233 # Set the TT template to use
234 $c->stash->{template} = 'books/form_create.tt2';
237 This action simply invokes a view containing a book creation form.
239 =head2 Add a Template for the Form
241 Open C<root/src/books/form_create.tt2> in your editor and enter:
243 [% META title = 'Manual Form Book Create' -%]
245 <form method="post" action="[% Catalyst.uri_for('form_create_do') %]">
247 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
248 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
249 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
251 <input type="submit" name="Submit" value="Submit">
254 Note that we have specified the target of the form data as
255 C<form_create_do>, the method created in the section that follows.
257 =head2 Add Method to Process Form Values and Update Database
259 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
260 save the form information to the databse:
262 =head2 form_create_do
264 Take information from form and add to database
268 sub form_create_do : Local {
271 # Retrieve the values from the form
272 my $title = $c->request->params->{title} || 'N/A';
273 my $rating = $c->request->params->{rating} || 'N/A';
274 my $author_id = $c->request->params->{author_id} || '1';
277 my $book = $c->model('MyAppDB::Book')->create({
281 # Handle relationship with author
282 $book->add_to_book_authors({author_id => $author_id});
284 # Store new model object in stash
285 $c->stash->{book} = $book;
287 # Avoid Data::Dumper issue mentioned earlier
288 # You can probably omit this
289 $Data::Dumper::Useperl = 1;
291 # Set the TT template to use
292 $c->stash->{template} = 'books/create_done.tt2';
296 =head2 Test Out The Form
298 If the application is still running from before, use C<Ctrl-C> to kill
299 it. Then restart the server:
301 $ script/myapp_server.pl
303 Point your browser to L<http://localhost:3000/books/form_create> and
304 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
305 author ID of 4. You should then be forwarded to the same
306 C<create_done.tt2> template seen in earlier examples. Finally, click
307 "Return to list" to view the full list of books.
309 B<Note:> Having the user enter the primary key ID for the author is
310 obviously crude; we will address this concern with a drop-down list in
313 =head1 A SIMPLE DELETE FEATURE
315 Turning out attention to the delete portion of CRUD, this section
316 illustrates some basic techniques that can be used to remove information
320 =head2 Include a Delete Link in the List
322 Edit C<root/src/books/list.tt2> and update it to the following (two
323 sections have changed: 1) the additional '<th>Links</th>' table header,
324 and 2) the four lines for the Delete link near the bottom).
326 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
327 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
328 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
329 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
331 [% # Provide a title to root/lib/site/header -%]
332 [% META title = 'Book List' -%]
335 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
336 [% # Display each book in a table row %]
337 [% FOREACH book IN books -%]
339 <td>[% book.title %]</td>
340 <td>[% book.rating %]</td>
342 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
343 [% # loop in 'side effect notation' to load just the last names of the -%]
344 [% # authors into the list. Note that we are making a bogus assignment to -%]
345 [% # the 'xx' vbl to avoid printing the size of the list after each push. -%]
347 xx = tt_authors.push(author.last_name) FOREACH author = book.authors %]
348 [% # Now use a TT 'virtual method' to display the author count -%]
349 ([% tt_authors.size %])
350 [% # Use another TT virtual method to join the names with comma separators -%]
351 [% tt_authors.join(', ') %]
354 [% # Add a link to delete a book %]
355 <a href="[% Catalyst.uri_for('delete/') _ book.id %]">Delete</a>
361 The additional code is obviously designed to add a new column to the
362 right side of the table with a C<Delete> "button" (for simplicity, links
363 will be used instead of full HTML buttons).
365 =head2 Add a Delete Action to the Controller
367 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
377 # $id = primary key of book to delete
378 my ($self, $c, $id) = @_;
380 # Search for the book and then delete it
381 $c->model('MyAppDB::Book')->search({id => $id})->delete_all;
383 # Set a status message to be displayed at the top of the view
384 $c->stash->{status_msg} = "Book deleted.";
386 # Forward to the list action/method in this controller
390 This method first deletes the book with the specified primary key ID.
391 However, it also removes the corresponding entry from the
392 C<book_authors> table. Note that C<delete_all> was used instead of
393 C<delete>: whereas C<delete_all> also removes the join table entries in
394 C<book_authors>, C<delete> does not.
396 Then, rather than forwarding to a "delete done" page as we did with the
397 earlier create example, it simply sets the C<status_msg> to display a
398 notification to the user as the normal list view is rendered.
400 The C<delete> action uses the context C<forward> method to return the
401 user to the book list. The C<detach> method could have also been used.
402 Whereas C<forward> I<returns> to the original action once it is
403 completed, C<detach> does I<not> return. Other than that, the two are
406 Another alternative to C<forward> would be to use
407 C<$c-E<gt>response-E<gt>redirect($c-E<gt>uri_for('/books/list'))>. The
408 C<forward> and C<redirect> operations differ in several important
409 respects that stem from the fact that redirects cause the client browser
410 to issue an entirely new HTTP request. In doing so, this results in a
411 new URL showing in the browser window. And, because the stash
412 information is reset for every request, the "Book deleted" message would
416 =head2 Try the Delete Feature
418 If the application is still running from before, use C<Ctrl-C> to kill
419 it. Then restart the server:
421 $ script/myapp_server.pl
423 Then point your browser to L<http://localhost:3000/books/list> and click
424 the "Delete" link next to "TCPIP_Illustrated_Vol-2". A green "Book
425 deleted" status message should display at the top of the page, along
426 with a list of the six remaining books.
431 Kennedy Clark, C<hkclark@gmail.com>
433 Please report any errors, issues or suggestions to the author. The
434 most recent version of the Catlayst Tutorial can be found at
435 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
437 Copyright 2006, Kennedy Clark, under Creative Commons License
438 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).