source: text-formbuilder/trunk/lib/Text/FormBuilder.pm @ 33

Last change on this file since 33 was 33, checked in by peter, 19 years ago

split _template into _pre_template and _post_template
BUGFIX: moved !pattern expansion to later
beginning work on custom messages

File size: 26.2 KB
Line 
1package Text::FormBuilder;
2
3use strict;
4use warnings;
5
6use vars qw($VERSION);
7
8$VERSION = '0.06_03';
9
10use Carp;
11use Text::FormBuilder::Parser;
12use CGI::FormBuilder;
13
14# the static default options passed to CGI::FormBuilder->new
15my %DEFAULT_OPTIONS = (
16    method => 'GET',
17    javascript => 0,
18    keepextras => 1,
19);
20
21# the built in CSS for the template
22my $DEFAULT_CSS = <<END;
23table { padding: 1em; }
24#author, #footer { font-style: italic; }
25caption h2 { padding: .125em .5em; background: #ccc; text-align: left; }
26th { text-align: left; }
27th h3 { padding: .125em .5em; background: #eee; }
28th.label { font-weight: normal; text-align: right; vertical-align: top; }
29td ul { list-style: none; padding-left: 0; margin-left: 0; }
30.sublabel { color: #999; }
31.invalid { background: red; }
32END
33
34my %DEFAULT_MESSAGES = (
35    text_formbuilder_created => 'Created by %s',
36    text_formbuilder_madewith => 'Made with %s',
37    text_formbuilder_required => 'Required fields are marked in <strong>bold</strong>.',
38);
39
40sub new {
41    my $invocant = shift;
42    my $class = ref $invocant || $invocant;
43    my $self = {
44        parser => Text::FormBuilder::Parser->new,
45    };
46    return bless $self, $class;
47}
48
49sub parse {
50    my ($self, $source) = @_;
51    if (ref $source && ref $source eq 'SCALAR') {
52        $self->parse_text($$source);
53    } else {
54        $self->parse_file($source);
55    }
56}
57
58sub parse_file {
59    my ($self, $filename) = @_;
60   
61    # so it can be called as a class method
62    $self = $self->new unless ref $self;
63   
64    local $/ = undef;
65    open SRC, "< $filename" or croak "[Text::FormBuilder::parse_file] Can't open $filename: $!" and return;
66    my $src = <SRC>;
67    close SRC;
68   
69    return $self->parse_text($src);
70}
71
72sub parse_text {
73    my ($self, $src) = @_;
74   
75    # so it can be called as a class method
76    $self = $self->new unless ref $self;
77   
78    # append a newline so that it can be called on a single field easily
79    $src .= "\n";
80   
81    $self->{form_spec} = $self->{parser}->form_spec($src);
82   
83    # mark structures as not built (newly parsed text)
84    $self->{built} = 0;
85   
86    return $self;
87}
88
89# this is where a lot of the magic happens
90sub build {
91    my ($self, %options) = @_;
92   
93    # our custom %options:
94    # form_only: use only the form part of the template
95    my $form_only = $options{form_only};
96   
97    # css, extra_css: allow for custom inline stylesheets
98    #   neat trick: extra_css => '@import(my_external_stylesheet.css);'
99    #   will let you use an external stylesheet
100    my $css;
101    $css = $options{css} || $DEFAULT_CSS;
102    $css .= $options{extra_css} if $options{extra_css};
103   
104    # messages
105    if ($options{messages}) {
106        # if its a hashref, we'll just pass it on to CGI::FormBuilder
107       
108        if (my $ref = ref $options{messages}) {
109            # hashref pass on to CGI::FormBuilder
110            croak "[Text::FormBuilder] Argument to 'messages' option must be a filename or hashref" unless $ref eq 'HASH';
111            while (my ($key,$value) = each %DEFAULT_MESSAGES) {
112                $options{messages}{$key} ||= $DEFAULT_MESSAGES{$key};
113            }
114        } else {
115            # filename, just *warn* on missing, and use defaults
116            if (-f $options{messages} && -r _ && open(MESSAGES, "< $options{messages}")) {
117                $options{messages} = {};
118                while(<MESSAGES>) {
119                    next if /^\s*#/ || /^\s*$/;
120                    chomp;
121                    my($key,$value) = split ' ', $_, 2;
122                    ($options{messages}{$key} = $value) =~ s/\s+$//;
123                }
124                close MESSAGES;
125            } else {
126                carp "Could not read messages file $options{messages}: $!";
127            }
128        }
129    }
130   
131    # save the build options so they can be used from write_module
132    $self->{build_options} = { %options };
133   
134    # remove our custom options before we hand off to CGI::FormBuilder
135    delete $options{$_} foreach qw(form_only css extra_css);
136   
137    # expand groups
138    my %groups = %{ $self->{form_spec}{groups} || {} };
139    for my $section (@{ $self->{form_spec}{sections} || [] }) {
140        foreach (grep { $$_[0] eq 'group' } @{ $$section{lines} }) {
141            $$_[1]{group} =~ s/^\%//;       # strip leading % from group var name
142           
143            if (exists $groups{$$_[1]{group}}) {
144                my @fields; # fields in the group
145                push @fields, { %$_ } foreach @{ $groups{$$_[1]{group}} };
146                for my $field (@fields) {
147                    $$field{label} ||= ucfirst $$field{name};
148                    $$field{name} = "$$_[1]{name}_$$field{name}";               
149                }
150                $_ = [ 'group', { label => $$_[1]{label} || ucfirst(join(' ',split('_',$$_[1]{name}))), group => \@fields } ];
151            }
152        }
153    }
154   
155    # the actual fields that are given to CGI::FormBuilder
156    $self->{form_spec}{fields} = [];
157   
158    for my $section (@{ $self->{form_spec}{sections} || [] }) {
159        for my $line (@{ $$section{lines} }) {
160            if ($$line[0] eq 'group') {
161                push @{ $self->{form_spec}{fields} }, $_ foreach @{ $$line[1]{group} };
162            } elsif ($$line[0] eq 'field') {
163                push @{ $self->{form_spec}{fields} }, $$line[1];
164            }
165        }
166    }
167   
168    # substitute in custom pattern definitions for field validation
169    if (my %patterns = %{ $self->{form_spec}{patterns} || {} }) {
170        foreach (@{ $self->{form_spec}{fields} }) {
171            if ($$_{validate} and exists $patterns{$$_{validate}}) {
172                $$_{validate} = $patterns{$$_{validate}};
173            }
174        }
175    }
176   
177    # substitute in list names
178    my %lists = %{ $self->{form_spec}{lists} || {} };
179    foreach (@{ $self->{form_spec}{fields} }) {
180        next unless $$_{list};
181       
182        $$_{list} =~ s/^\@//;   # strip leading @ from list var name
183       
184        # a hack so we don't get screwy reference errors
185        if (exists $lists{$$_{list}}) {
186            my @list;
187            push @list, { %$_ } foreach @{ $lists{$$_{list}} };
188            $$_{options} = \@list;
189        } else {
190            # assume that the list name is a builtin
191            # and let it fall through to CGI::FormBuilder
192            $$_{options} = $$_{list};
193        }
194    } continue {
195        delete $$_{list};
196    }
197   
198    # special case single-value checkboxes
199    foreach (grep { $$_{type} && $$_{type} eq 'checkbox' } @{ $self->{form_spec}{fields} }) {
200        unless ($$_{options}) {
201            $$_{options} = [ { $$_{name} => $$_{label} || ucfirst join(' ',split(/_/,$$_{name})) } ];
202        }
203    }
204   
205    # TODO: configurable threshold for this
206    foreach (@{ $self->{form_spec}{fields} }) {
207        $$_{ulist} = 1 if ref $$_{options} and @{ $$_{options} } >= 3;
208    }
209   
210    # remove extraneous undefined values
211    for my $field (@{ $self->{form_spec}{fields} }) {
212        defined $$field{$_} or delete $$field{$_} foreach keys %{ $field };
213    }
214   
215    # remove false $$_{required} params because this messes up things at
216    # the CGI::FormBuilder::field level; it seems to be marking required
217    # based on the existance of a 'required' param, not whether it is
218    # true or defined
219    $$_{required} or delete $$_{required} foreach @{ $self->{form_spec}{fields} };
220
221    $self->{form} = CGI::FormBuilder->new(
222        %DEFAULT_OPTIONS,
223        # need to explicity set the fields so that simple text fields get picked up
224        fields   => [ map { $$_{name} } @{ $self->{form_spec}{fields} } ],
225        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
226        title => $self->{form_spec}{title},
227        text  => $self->{form_spec}{description},
228        template => {
229            type => 'Text',
230            engine => {
231                TYPE       => 'STRING',
232                SOURCE     => $form_only ? $self->_form_template : $self->_template($css),
233                DELIMITERS => [ qw(<% %>) ],
234            },
235            data => {
236                sections    => $self->{form_spec}{sections},
237                author      => $self->{form_spec}{author},
238                description => $self->{form_spec}{description},
239            },
240        },
241        %options,
242    );
243    $self->{form}->field(%{ $_ }) foreach @{ $self->{form_spec}{fields} };
244   
245    # mark structures as built
246    $self->{built} = 1;
247   
248    return $self;
249}
250
251sub write {
252    my ($self, $outfile) = @_;
253   
254    # automatically call build if needed to
255    # allow the new->parse->write shortcut
256    $self->build unless $self->{built};
257   
258    if ($outfile) {
259        open FORM, "> $outfile";
260        print FORM $self->form->render;
261        close FORM;
262    } else {
263        print $self->form->render;
264    }
265}
266
267sub write_module {
268    my ($self, $package, $use_tidy) = @_;
269
270    croak '[Text::FormBuilder::write_module] Expecting a package name' unless $package;
271   
272    # automatically call build if needed to
273    # allow the new->parse->write shortcut
274    $self->build unless $self->{built};
275   
276    # conditionally use Data::Dumper
277    eval 'use Data::Dumper;';
278    die "Can't write module; need Data::Dumper. $@" if $@;
279   
280    $Data::Dumper::Terse = 1;           # don't dump $VARn names
281    $Data::Dumper::Quotekeys = 0;       # don't quote simple string keys
282   
283    my $css;
284    $css = $self->{build_options}{css} || $DEFAULT_CSS;
285    $css .= $self->{build_options}{extra_css} if $self->{build_options}{extra_css};
286   
287    my %options = (
288        %DEFAULT_OPTIONS,
289        title => $self->{form_spec}{title},
290        text  => $self->{form_spec}{description},
291        fields   => [ map { $$_{name} } @{ $self->{form_spec}{fields} } ],
292        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
293        template => {
294            type => 'Text',
295            engine => {
296                TYPE       => 'STRING',
297                SOURCE     => $self->{build_options}{form_only} ? $self->_form_template : $self->_template($css),
298                DELIMITERS => [ qw(<% %>) ],
299            },
300            data => {
301                sections    => $self->{form_spec}{sections},
302                author      => $self->{form_spec}{author},
303                description => $self->{form_spec}{description},
304            },
305        }, 
306        %{ $self->{build_options} },
307    );
308   
309    # remove our custom options
310    delete $options{$_} foreach qw(form_only css extra_css);
311   
312    my $form_options = keys %options > 0 ? Data::Dumper->Dump([\%options],['*options']) : '';
313   
314    my $field_setup = join(
315        "\n", 
316        map { '$cgi_form->field' . Data::Dumper->Dump([$_],['*field']) . ';' } @{ $self->{form_spec}{fields} }
317    );
318   
319    my $module = <<END;
320package $package;
321use strict;
322use warnings;
323
324use CGI::FormBuilder;
325
326sub get_form {
327    my \$cgi = shift;
328    my \$cgi_form = CGI::FormBuilder->new(
329        params => \$cgi,
330        $form_options
331    );
332   
333    $field_setup
334   
335    return \$cgi_form;
336}
337
338# module return
3391;
340END
341
342    my $outfile = (split(/::/, $package))[-1] . '.pm';
343   
344    if ($use_tidy) {
345        # clean up the generated code, if asked
346        eval 'use Perl::Tidy';
347        die "Can't tidy the code: $@" if $@;
348        Perl::Tidy::perltidy(source => \$module, destination => $outfile, argv => '-nolq -ci=4');
349    } else {
350        # otherwise, just print as is
351        open FORM, "> $outfile";
352        print FORM $module;
353        close FORM;
354    }
355}
356
357sub form {
358    my $self = shift;
359   
360    # automatically call build if needed to
361    # allow the new->parse->write shortcut
362    $self->build unless $self->{built};
363
364    return $self->{form};
365}
366
367sub _form_template {
368    my $self = shift;
369    #warn keys %{ $self->{build_options}{messages} };
370    my $msg_required = $self->{build_options}{messages}{text_formbuilder_required};
371    return q[<% $description ? qq[<p id="description">$description</p>] : '' %>
372<% (grep { $_->{required} } @fields) ? qq[<p id="instructions">(Required fields are marked in <strong>bold</strong>.)</p>] : '' %>
373<% $start %>
374<%
375    # drop in the hidden fields here
376    $OUT = join("\n", map { $$_{field} } grep { $$_{type} eq 'hidden' } @fields);
377%>
378
379<%
380    SECTION: while (my $section = shift @sections) {
381        $OUT .= qq[<table id="] . ($$section{id} || '_default') . qq[">\n];
382        $OUT .= qq[  <caption><h2 class="sectionhead">$$section{head}</h2></caption>] if $$section{head};
383        TABLE_LINE: for my $line (@{ $$section{lines} }) {
384            if ($$line[0] eq 'head') {
385                $OUT .= qq[  <tr><th class="subhead" colspan="2"><h3>$$line[1]</h3></th></tr>\n]
386            } elsif ($$line[0] eq 'field') {
387                #TODO: we only need the field names, not the full field spec in the lines strucutre
388                local $_ = $field{$$line[1]{name}};
389                # skip hidden fields in the table
390                next TABLE_LINE if $$_{type} eq 'hidden';
391               
392                $OUT .= $$_{invalid} ? qq[  <tr class="invalid">] : qq[  <tr>];
393               
394                # special case single value checkboxes
395                if ($$_{type} eq 'checkbox' && @{ $$_{options} } == 1) {
396                    $OUT .= qq[<th></th>];
397                } else {
398                    $OUT .= '<th class="label">' . ($$_{required} ? qq[<strong class="required">$$_{label}:</strong>] : "$$_{label}:") . '</th>';
399                }
400               
401                # mark invalid fields
402                if ($$_{invalid}) {
403                    $OUT .= qq[<td>$$_{field} $$_{comment} Missing or invalid value.</td>];
404                } else {
405                    $OUT .= qq[<td>$$_{field} $$_{comment}</td>];
406                }
407               
408                $OUT .= qq[</tr>\n];
409               
410            } elsif ($$line[0] eq 'group') {
411                my @field_names = map { $$_{name} } @{ $$line[1]{group} };
412                my @group_fields = map { $field{$_} } @field_names;
413                $OUT .= (grep { $$_{invalid} } @group_fields) ? qq[  <tr class="invalid">\n] : qq[  <tr>\n];
414               
415                $OUT .= '    <th class="label">';
416                $OUT .= (grep { $$_{required} } @group_fields) ? qq[<strong class="required">$$line[1]{label}:</strong>] : "$$line[1]{label}:";
417                $OUT .= qq[</th>\n];
418               
419                $OUT .= qq[    <td>];
420                $OUT .= join(' ', map { qq[<small class="sublabel">$$_{label}</small> $$_{field} $$_{comment}] } @group_fields);
421                $OUT .= qq[    </td>\n];
422                $OUT .= qq[  </tr>\n];
423            }   
424        }
425        # close the table if there are sections remaining
426        # but leave the last one open for the submit button
427        $OUT .= qq[</table>\n] if @sections;
428    }
429%>
430  <tr><th></th><td style="padding-top: 1em;"><% $submit %></td></tr>
431</table>
432<% $end %>
433];
434}
435
436sub _pre_template {
437    my $self = shift;
438    my $css = shift || $DEFAULT_CSS;
439    return 
440q[<html>
441<head>
442  <title><% $title %><% $author ? ' - ' . ucfirst $author : '' %></title>
443  <style type="text/css">
444] .
445$css .
446q[  </style>
447  <% $jshead %>
448</head>
449<body>
450
451<h1><% $title %></h1>
452<% $author ? qq[<p id="author">Created by $author</p>] : '' %>
453];
454}
455
456sub _post_template {
457q[<hr />
458<div id="footer">
459  <p id="creator">Made with <a href="http://formbuilder.org/">CGI::FormBuilder</a> version <% CGI::FormBuilder->VERSION %>.</p>
460</div>
461</body>
462</html>
463];
464}
465
466sub _template {
467    my $self = shift;
468    my $css = shift || $DEFAULT_CSS;
469    return $self->_pre_template($css) . $self->_form_template . $self->_post_template;
470}
471
472sub dump { 
473    eval "use YAML;";
474    unless ($@) {
475        print YAML::Dump(shift->{form_spec});
476    } else {
477        warn "Can't dump form spec structure: $@";
478    }
479}
480
481
482# module return
4831;
484
485=head1 NAME
486
487Text::FormBuilder - Create CGI::FormBuilder objects from simple text descriptions
488
489=head1 SYNOPSIS
490
491    use Text::FormBuilder;
492   
493    my $parser = Text::FormBuilder->new;
494    $parser->parse($src_file);
495   
496    # returns a new CGI::FormBuilder object with
497    # the fields from the input form spec
498    my $form = $parser->form;
499   
500    # write a My::Form module to Form.pm
501    $parser->write_module('My::Form');
502
503=head1 REQUIRES
504
505L<Parse::RecDescent>, L<CGI::FormBuilder>, L<Text::Template>
506
507=head1 DESCRIPTION
508
509=head2 new
510
511=head2 parse
512
513    # parse a file
514    $parser->parse($filename);
515   
516    # or pass a scalar ref for parse a literal string
517    $parser->parse(\$string);
518
519Parse the file or string. Returns the parser object.
520
521=head2 parse_file
522
523    $parser->parse_file($src_file);
524   
525    # or as a class method
526    my $parser = Text::FormBuilder->parse($src_file);
527
528=head2 parse_text
529
530    $parser->parse_text($src);
531
532Parse the given C<$src> text. Returns the parser object.
533
534=head2 build
535
536    $parser->build(%options);
537
538Builds the CGI::FormBuilder object. Options directly used by C<build> are:
539
540=over
541
542=item C<form_only>
543
544Only uses the form portion of the template, and omits the surrounding html,
545title, author, and the standard footer. This does, however, include the
546description as specified with the C<!description> directive.
547
548=item C<css>, C<extra_css>
549
550These options allow you to tell Text::FormBuilder to use different
551CSS styles for the built in template. A value given a C<css> will
552replace the existing CSS, and a value given as C<extra_css> will be
553appended to the CSS. If both options are given, then the CSS that is
554used will be C<css> concatenated with C<extra_css>.
555
556=back
557
558All other options given to C<build> are passed on verbatim to the
559L<CGI::FormBuilder> constructor. Any options given here override the
560defaults that this module uses.
561
562The C<form>, C<write>, and C<write_module> methods will all call
563C<build> with no options for you if you do not do so explicitly.
564This allows you to say things like this:
565
566    my $form = Text::FormBuilder->new->parse('formspec.txt')->form;
567
568However, if you need to specify options to C<build>, you must call it
569explictly after C<parse>.
570
571=head2 form
572
573    my $form = $parser->form;
574
575Returns the L<CGI::FormBuilder> object. Remember that you can modify
576this object directly, in order to (for example) dynamically populate
577dropdown lists or change input types at runtime.
578
579=head2 write
580
581    $parser->write($out_file);
582    # or just print to STDOUT
583    $parser->write;
584
585Calls C<render> on the FormBuilder form, and either writes the resulting
586HTML to a file, or to STDOUT if no filename is given.
587
588CSS Hint: to get multiple sections to all line up their fields, set a
589standard width for th.label
590
591=head2 write_module
592
593    $parser->write_module($package, $use_tidy);
594
595Takes a package name, and writes out a new module that can be used by your
596CGI script to render the form. This way, you only need CGI::FormBuilder on
597your server, and you don't have to parse the form spec each time you want
598to display your form. The generated module has one function (not exported)
599called C<get_form>, that takes a CGI object as its only argument, and returns
600a CGI::FormBuilder object.
601
602First, you parse the formspec and write the module, which you can do as a one-liner:
603
604    $ perl -MText::FormBuilder -e"Text::FormBuilder->parse('formspec.txt')->write_module('My::Form')"
605
606And then, in your CGI script, use the new module:
607
608    #!/usr/bin/perl -w
609    use strict;
610   
611    use CGI;
612    use My::Form;
613   
614    my $q = CGI->new;
615    my $form = My::Form::get_form($q);
616   
617    # do the standard CGI::FormBuilder stuff
618    if ($form->submitted && $form->validate) {
619        # process results
620    } else {
621        print $q->header;
622        print $form->render;
623    }
624
625If you pass a true value as the second argument to C<write_module>, the parser
626will run L<Perl::Tidy> on the generated code before writing the module file.
627
628    # write tidier code
629    $parser->write_module('My::Form', 1);
630
631=head2 dump
632
633Uses L<YAML> to print out a human-readable representation of the parsed
634form spec.
635
636=head1 DEFAULTS
637
638These are the default settings that are passed to C<< CGI::FormBuilder->new >>:
639
640    method => 'GET'
641    javascript => 0
642    keepextras => 1
643
644Any of these can be overriden by the C<build> method:
645
646    # use POST instead
647    $parser->build(method => 'POST')->write;
648
649=head1 LANGUAGE
650
651    field_name[size]|descriptive label[hint]:type=default{option1[display string],...}//validate
652   
653    !title ...
654   
655    !author ...
656   
657    !description {
658        ...
659    }
660   
661    !pattern name /regular expression/
662   
663    !list name {
664        option1[display string],
665        option2[display string],
666        ...
667    }
668   
669    !list name &{ CODE }
670   
671    !section id heading
672   
673    !head ...
674
675=head2 Directives
676
677=over
678
679=item C<!pattern>
680
681Defines a validation pattern.
682
683=item C<!list>
684
685Defines a list for use in a C<radio>, C<checkbox>, or C<select> field.
686
687=item C<!title>
688
689=item C<!author>
690
691=item C<!description>
692
693A brief description of the form. Suitable for special instructions on how to
694fill out the form.
695
696=item C<!section>
697
698Starts a new section. Each section has its own heading and id, which are
699written by default into spearate tables.
700
701=item C<!head>
702
703Inserts a heading between two fields. There can only be one heading between
704any two fields; the parser will warn you if you try to put two headings right
705next to each other.
706
707=back
708
709=head2 Fields
710
711First, a note about multiword strings in the fields. Anywhere where it says
712that you may use a multiword string, this means that you can do one of two
713things. For strings that consist solely of alphanumeric characters (i.e.
714C<\w+>) and spaces, the string will be recognized as is:
715
716    field_1|A longer label
717
718If you want to include non-alphanumerics (e.g. punctuation), you must
719single-quote the string:
720
721    field_2|'Dept./Org.'
722
723To include a literal single-quote in a single-quoted string, escape it with
724a backslash:
725
726    field_3|'\'Official\' title'
727
728Now, back to the basics. Form fields are each described on a single line.
729The simplest field is just a name (which cannot contain any whitespace):
730
731    color
732
733This yields a form with one text input field of the default size named `color'.
734The label for this field as generated by CGI::FormBuilder would be ``Color''.
735To add a longer or more descriptive label, use:
736
737    color|Favorite color
738
739The descriptive label can be a multiword string, as described above.
740
741To use a different input type:
742
743    color|Favorite color:select{red,blue,green}
744
745Recognized input types are the same as those used by CGI::FormBuilder:
746
747    text        # the default
748    textarea
749    password
750    file
751    checkbox
752    radio
753    select
754    hidden
755    static
756
757To change the size of the input field, add a bracketed subscript after the
758field name (but before the descriptive label):
759
760    # for a single line field, sets size="40"
761    title[40]:text
762   
763    # for a multiline field, sets rows="4" and cols="30"
764    description[4,30]:textarea
765
766For the input types that can have options (C<select>, C<radio>, and
767C<checkbox>), here's how you do it:
768
769    color|Favorite color:select{red,blue,green}
770
771Values are in a comma-separated list of single words or multiword strings
772inside curly braces. Whitespace between values is irrelevant.
773
774To add more descriptive display text to a value in a list, add a square-bracketed
775``subscript,'' as in:
776
777    ...:select{red[Scarlet],blue[Azure],green[Olive Drab]}
778
779If you have a list of options that is too long to fit comfortably on one line,
780you should use the C<!list> directive:
781
782    !list MONTHS {
783        1[January],
784        2[February],
785        3[March],
786        # and so on...
787    }
788   
789    month:select@MONTHS
790
791There is another form of the C<!list> directive: the dynamic list:
792
793    !list RANDOM &{ map { rand } (0..5) }
794
795The code inside the C<&{ ... }> is C<eval>ed by C<build>, and the results
796are stuffed into the list. The C<eval>ed code can either return a simple
797list, as the example does, or the fancier C<< ( { value1 => 'Description 1'},
798{ value2 => 'Description 2}, ... ) >> form.
799
800I<B<NOTE:> This feature of the language may go away unless I find a compelling
801reason for it in the next few versions. What I really wanted was lists that
802were filled in at run-time (e.g. from a database), and that can be done easily
803enough with the CGI::FormBuilder object directly.>
804
805If you want to have a single checkbox (e.g. for a field that says ``I want to
806recieve more information''), you can just specify the type as checkbox without
807supplying any options:
808
809    moreinfo|I want to recieve more information:checkbox
810
811In this case, the label ``I want to recieve more information'' will be
812printed to the right of the checkbox.
813
814You can also supply a default value to the field. To get a default value of
815C<green> for the color field:
816
817    color|Favorite color:select=green{red,blue,green}
818
819Default values can also be either single words or multiword strings.
820
821To validate a field, include a validation type at the end of the field line:
822
823    email|Email address//EMAIL
824
825Valid validation types include any of the builtin defaults from L<CGI::FormBuilder>,
826or the name of a pattern that you define with the C<!pattern> directive elsewhere
827in your form spec:
828
829    !pattern DAY /^([1-3][0-9])|[1-9]$/
830   
831    last_day//DAY
832
833If you just want a required value, use the builtin validation type C<VALUE>:
834
835    title//VALUE
836
837By default, adding a validation type to a field makes that field required. To
838change this, add a C<?> to the end of the validation type:
839
840    contact//EMAIL?
841
842In this case, you would get a C<contact> field that was optional, but if it
843were filled in, would have to validate as an C<EMAIL>.
844
845=head2 Comments
846
847    # comment ...
848
849Any line beginning with a C<#> is considered a comment.
850
851=head1 TODO
852
853Allow for custom wrappers around the C<form_template>
854
855Use the custom message file format for messages in the built in template (i18n/l10n)
856
857Maybe use HTML::Template instead of Text::Template for the built in template
858(since CGI::FormBuilder users may be more likely to already have HTML::Template)
859
860Better examples in the docs (maybe a standalone or two as well)
861
862Document the defaults that are passed to CGI::FormBuilder
863
864C<!include> directive to include external formspec files
865
866Better tests!
867
868=head1 BUGS
869
870I'm sure they're in there, I just haven't tripped over any new ones lately. :-)
871
872=head1 SEE ALSO
873
874L<CGI::FormBuilder>
875
876=head1 THANKS
877
878Thanks to eszpee for pointing out some bugs in the default value parsing,
879as well as some suggestions for i18n/l10n and splitting up long forms into
880sections.
881
882=head1 AUTHOR
883
884Peter Eichman <peichman@cpan.org>
885
886=head1 COPYRIGHT AND LICENSE
887
888Copyright E<copy>2004 by Peter Eichman.
889
890This program is free software; you can redistribute it and/or
891modify it under the same terms as Perl itself.
892
893=cut
Note: See TracBrowser for help on using the repository browser.