4 Maypole::Manual::StandardTemplates - Maypole's Standard Templates and Actions
8 As we saw in our Create-Read-Update-Delete (CRUD) example,
9 Maypole does all it can to make your life
10 easier; this inclues providing a set of default actions and
11 factory-supplied templates. These are written in such a generic way,
12 making extensive use of class metadata, that they are more or less
13 applicable to any table or application. However, in order to progress
14 from automatically generated CRUD applications to real customized
15 applications, we need to begin by understanding how these default
16 actions do their stuff, and how the default templates are put together.
17 Once we have an understanding of what Maypole does for us automatically,
18 we can begin to customize and create our own templates and actions.
20 Although the standard templates can be applied in many situations,
21 they're really provided just as examples,
22 as a starting point to create your own templates to suit your needs.
23 The goal of templating is to keep templates simple so the presentation
24 can be changed easily when you desire.
25 We're not trying to build a single set of reusable templates that cover
26 every possible situation.
28 =head2 The standard actions
30 Remember that actions are just subroutines in the model classes with an
31 I<Exported> attribute.
32 A simple, uncustomized Maypole model class, such as one of the classes
33 in the beer database application, provides the following default actions
34 - that is, provides access to the following URLs:
38 =item C</[table]/view/[id]>
40 This takes the ID of an object in a table, retrieves the object, and
41 presents it to the F<view> template.
43 =item C</[table]/edit/[id]>
45 This is the same as C<view>, but uses the F<edit> template to provide a
46 web form to edit the object; it submits to C<do_edit>.
48 =item C</[table]/do_edit/[id]>
50 When called with an ID, the C<do_edit> action provides row editing.
52 =item C</[table]/do_edit/>
54 When called without an ID, the C<do_edit> action provides row creation.
56 =item C</[table]/delete/id>
58 This deletes a row, returning to the C<list> page.
60 =item C</[table]/list/>
62 This provides a paged list of the table suitable for browsing.
64 =item C</[table]/search/>
66 This handles a search query and presents the search results back to the
71 We'll now look at how these actions are implemented, before moving on to
72 take a detailed look at the templates they drive.
74 =head3 C<view> and C<edit>
76 These actions are very simple; their job is to take a row ID, turn it
77 into an object, and hand it to the template to be displayed. However, as
78 taking the first argument and turning it into an object is such a common
79 action, it is handled directly by the model class's C<process> method.
80 Similarly, the default template name provided by the C<process> method
81 is the name of the action, and so will be C<view> or C<edit>
84 So the code required to make these two actions work turns out to be:
86 sub view :Exported { }
87 sub edit :Exported { }
89 That's right - no code at all. This shows the power of the templating
90 side of the system. If you think about it for a moment, it is natural
91 that these actions should not have any code - after all, we have
92 separated out the concerns of "acting" and displaying. Both of these
93 "actions" are purely concerned with displaying a record, and don't need
94 to do any "acting". Remember that the "edit" method doesn't actually do
95 any editing - this is provided by C<do_edit>; it is just another view of
96 the data, albeit one which allows the data to be modified later. These
97 two methods don't need to modify the row in any way, they don't need to
98 do anything clever. They just are.
100 So why do we need the subroutines at all? If the subroutines did not exist,
101 we would be sent to the C<view> and C<edit> templates as would be
102 expected, but these templates would not be provided with the right
103 arguments; we need to go through the C<process> method in order to turn
104 the URL argument into a row and thence into an object to be fed to the
105 template. By exporting these methods, even though they contain no code
106 themselves, we force Maypole to call C<process> and provide the class
107 and object to the templates.
109 The moral of this story is that if you need to have an action which is
110 purely concerned with display, not acting, but needs to receive an ID
111 and turn it into an object, then create an empty method. For instance,
112 if we want to make an alternate view of a row which only showed the
113 important columns, we might create a method
115 sub short_view :Exported {}
117 This will cause the row to be turned into an object and fed to the
118 C<short_view> template, and that template would be responsible for
119 selecting the particular columns to be displayed.
123 This action, on the other hand, actually has to do something. If it's
124 provided with an ID, this is turned into an object and we're in edit
125 mode, acting upon that object. If not, we're in create mode.
127 sub do_edit :Exported {
129 my $h = CGI::Untaint->new(%{$r->params});
130 my ($obj) = @{$r->objects || []};
132 # We have something to edit
133 $obj->update_from_cgi($h);
135 $obj = $self->create_from_cgi($h);
138 The C<CDBI> model uses the C<update_from_cgi> and C<create_from_cgi>
139 methods of L<Class::DBI::FromCGI> to turn C<POST> parameters
140 into database table data. This in turn uses L<CGI::Untaint> to ensure
141 that the data coming in is suitable for the table. If you're using the
142 default C<CDBI> model, then, you're going to need to set up your tables
143 in a way that makes C<FromCGI> happy.
145 The data is untainted, and any errors are collected into a hash which is
146 passed to the template. We also pass back in the parameters, so that the
147 template can re-fill the form fields with the original values. The user
148 is then sent back to the C<edit> template.
150 if (my %errors = $obj->cgi_update_errors) {
151 # Set it up as it was:
152 $r->template_args->{cgi_params} = $r->params;
153 $r->template_args->{errors} = \%errors;
154 $r->template("edit");
157 Otherwise, the user is taken back to viewing the new object:
160 $r->template("view");
162 $r->objects([ $obj ]);
164 Notice that this does use hard-coded names for the templates to go to next.
165 Feel free to override this in your subclasses:
167 sub do_edit :Exported {
168 my ($class, $r) = @_;
169 $class->SUPER::do_edit($r);
170 $r->template("my_edit");
173 =head3 Digression on C<Class::DBI::FromCGI>
175 C<CGI::Untaint> is a mechanism for testing that incoming form data
176 conforms to various properties. For instance, given a C<CGI::Untaint>
177 object that encapsulates some C<POST> parameters, we can extract an
180 $h->extract(-as_integer => "score");
182 This checks that the C<score> parameter is an integer, and returns it if
183 it is; if not, C<< $h->error >> will be set to an appropriate error
184 message. Other tests by which you can extract your data are C<as_hex>
185 and C<as_printable>, which tests for a valid hex number and an ordinary
186 printable string respectively; there are other handlers available on
187 CPAN, and you can make your own, as documented in L<CGI::Untaint>.
189 To tell the C<FromCGI> handler what handler to use for each of your
190 columns, you need to use the C<untaint_columns> methods in the classes
191 representing your tables. For instance:
193 BeerDB::Beer->untaint_columns(
194 integer => ["score", ... ],
197 This must be done after the call to C<setup> in your handler, because
198 otherwise the model classes won't have been set up to inherit from
199 C<Class::DBI::FromCGI>.
201 Remember that if you want to use drop-downs to set the value of related
202 fields, such as the brewery for a beer, you need to untaint these as
203 something acceptable for the primary key of that table:
205 BeerDB::Beer->untaint_columns(
206 integer => ["score", "brewery", "style" ],
210 This is usually integer, if you're using numeric IDs for your primary
211 key. If not, you probably want C<printable>, but you probably know what
216 The delete method takes a number of arguments and deletes those rows from the
217 database; it then loads up all rows and heads to the F<list> template.
218 You almost certainly want to override this to provide some kind of
223 Listing, like viewing, is a matter of selecting objects for
224 presentation. This time, instead of a single object specified in the
225 URL, we want, by default, all the records in the table:
228 my ($class, $r) = @_;
229 $r->objects([ $self->retrieve_all ])
232 However, things are slightly complicated by paging and ordering by
233 column; the default implementation also provides a C<Class::DBI::Pager>
234 object to the templates and uses that to retrieve the appropriate bit of
235 the data, as specified by the C<page> URL query parameter. See the
236 L<"pager"> template below.
240 Searching also uses paging, and creates a query from the C<POST>
241 parameters. It uses the F<list> template to display the objects once
242 they've been selected from the database.
244 =head2 The templates and macros
246 Once these actions have done their work, they hand a set of objects to
247 the templates; if you haven't specified your own custom template
248 globally or for a given class, you'll be using the factory specified
249 template. Let's take a look now at each of these and how they're put
252 The beauty of the factory specified templates is that they make use of
253 the classes' metadata as supplied by the view class. Although you're
254 strongly encouraged to write your own templates, in which you don't need
255 to necessarily be as generic, the factory templates will always do the
256 right thing for any class without further modification, and as such are
257 useful examples of how to build Maypole templates.
261 There are certain common elements to a template, and these are extracted
262 out. For instance, all the templates call the F<header> template to
263 output a HTML header, and nearly all include the F<macros> template to
264 load up some common template functions. We'll look at these common
265 macros as we come across them.
273 The F<edit> template is pretty much the same as F<view>, but it uses
274 L<Class::DBI::AsForm>'s
275 C<to_field> method on each column of an object to return a C<HTML::Element>
276 object representing a form element to edit that property. These elements
277 are then rendered to HTML with C<as_HTML> or to XHTML with C<as_XML>.
278 It expects to see a list of
279 editing errors, if any, in the C<errors> template variable:
281 FOR col = classmetadata.columns;
284 "<B>"; classmetadata.colnames.$col; "</B>";
286 item.to_field(col).as_HTML;
289 "<FONT COLOR=\"#ff0000\">"; errors.$col; "</FONT>";
295 Browsing records and search results are both handled by the F<list> template.
296 The C<search> template argument is used to distinguish between the two cases:
299 <h2> Search results </h2>
301 <h2> Listing of all [% classmetadata.plural %]</h2>
306 The pager template controls the list of pages at the bottom (by default)
307 of the list and search views. It expects a C<pager> template argument
308 which responds to the L<Data::Page> interface.
309 There's a description of how it works in
310 L<the Template Toolkit section|Maypole::Manual::View/"The Template Toolkit">
315 The F<macros> template is included at the start of most other templates
316 and makes some generally-useful template macros available:
320 =item C<link(table, command, additional, label)>
322 This makes an HTML link pointing to C</base/table/command/additional>
323 labelled by the text in I<label>. C<base> is the template variable that
324 contains the base URL of this application.
326 =item C<maybe_link_view(object)>
328 C<maybe_link_view> takes something returned from the database - either
329 some ordinary data, or an object in a related class expanded by a
330 has-a relationship. If it is an object, it constructs a link to the view
331 command for that object. Otherwise, it just displays the data.
333 =item C<display_line(object)>
335 C<display_line> is used in the list template to display a row from the
336 database, by iterating over the columns and displaying the data for each
337 column. It misses out the C<id> column by default, and magically
338 URLifies columns called C<url>. This may be considered too much magic
341 =item C<button(object, action)>
343 This is a simple button that is submitted to C</base/table/action/id>,
344 where C<table> and C<id> are those belonging to the database row C<object>.
345 The button is labelled with the name of the action.
346 You can see buttons on many pages, including lists.
348 =item C<view_related(object)>
350 This takes an object, and looks up its C<related_accessors>; this gives
351 a list of accessor methods that can be called to get a list of related
352 objects. It then displays a title for that accessor, (e.g. "Beers" for a
353 C<brewery.beers>) calls the accessor, and displays a list of the results.
354 You can see it in use at the bottom of the standard view pages.
360 =head2 Customizing Generic CRUD Applications
366 L<Contents|Maypole::Manual>,
367 Next L<The Request Workflow|Maypole::Manual::Workflow>,
368 Previous L<Maypole View Classes|Maypole::Manual::View>,