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

Last change on this file since 33 was 33, checked in by peter, 20 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
RevLine 
[1]1package Text::FormBuilder;
2
3use strict;
4use warnings;
5
[19]6use vars qw($VERSION);
[1]7
[33]8$VERSION = '0.06_03';
[19]9
[16]10use Carp;
[1]11use Text::FormBuilder::Parser;
12use CGI::FormBuilder;
13
[28]14# the static default options passed to CGI::FormBuilder->new
[23]15my %DEFAULT_OPTIONS = (
16    method => 'GET',
17    javascript => 0,
18    keepextras => 1,
19);
20
[30]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
[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
[1]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 {
[19]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 {
[1]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;
[32]65    open SRC, "< $filename" or croak "[Text::FormBuilder::parse_file] Can't open $filename: $!" and return;
[1]66    my $src = <SRC>;
67    close SRC;
68   
69    return $self->parse_text($src);
70}
71
72sub parse_text {
73    my ($self, $src) = @_;
[16]74   
[1]75    # so it can be called as a class method
76    $self = $self->new unless ref $self;
[16]77   
[32]78    # append a newline so that it can be called on a single field easily
79    $src .= "\n";
80   
[1]81    $self->{form_spec} = $self->{parser}->form_spec($src);
[16]82   
83    # mark structures as not built (newly parsed text)
84    $self->{built} = 0;
85   
[1]86    return $self;
87}
88
[33]89# this is where a lot of the magic happens
[1]90sub build {
91    my ($self, %options) = @_;
[12]92   
93    # our custom %options:
94    # form_only: use only the form part of the template
95    my $form_only = $options{form_only};
[33]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
[30]100    my $css;
101    $css = $options{css} || $DEFAULT_CSS;
102    $css .= $options{extra_css} if $options{extra_css};
[12]103   
[33]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            }
[1]128        }
129    }
130   
[33]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   
[21]137    # expand groups
[28]138    my %groups = %{ $self->{form_spec}{groups} || {} };
[29]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 } ];
[21]151            }
152        }
153    }
[1]154   
[33]155    # the actual fields that are given to CGI::FormBuilder
[21]156    $self->{form_spec}{fields} = [];
[29]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            }
[21]165        }
166    }
167   
[33]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   
[1]177    # substitute in list names
[28]178    my %lists = %{ $self->{form_spec}{lists} || {} };
[25]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 {
[32]190            # assume that the list name is a builtin
191            # and let it fall through to CGI::FormBuilder
192            $$_{options} = $$_{list};
[1]193        }
[25]194    } continue {
195        delete $$_{list};
[30]196    }
[21]197   
[30]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   
[16]205    # TODO: configurable threshold for this
[14]206    foreach (@{ $self->{form_spec}{fields} }) {
[32]207        $$_{ulist} = 1 if ref $$_{options} and @{ $$_{options} } >= 3;
[14]208    }
[1]209   
[24]210    # remove extraneous undefined values
211    for my $field (@{ $self->{form_spec}{fields} }) {
212        defined $$field{$_} or delete $$field{$_} foreach keys %{ $field };
213    }
214   
[33]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
[24]219    $$_{required} or delete $$_{required} foreach @{ $self->{form_spec}{fields} };
[23]220
[1]221    $self->{form} = CGI::FormBuilder->new(
[23]222        %DEFAULT_OPTIONS,
[33]223        # need to explicity set the fields so that simple text fields get picked up
[29]224        fields   => [ map { $$_{name} } @{ $self->{form_spec}{fields} } ],
[24]225        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
226        title => $self->{form_spec}{title},
[25]227        text  => $self->{form_spec}{description},
[1]228        template => {
229            type => 'Text',
230            engine => {
231                TYPE       => 'STRING',
[30]232                SOURCE     => $form_only ? $self->_form_template : $self->_template($css),
[11]233                DELIMITERS => [ qw(<% %>) ],
[1]234            },
235            data => {
[29]236                sections    => $self->{form_spec}{sections},
[14]237                author      => $self->{form_spec}{author},
238                description => $self->{form_spec}{description},
[1]239            },
240        },
241        %options,
242    );
243    $self->{form}->field(%{ $_ }) foreach @{ $self->{form_spec}{fields} };
244   
[16]245    # mark structures as built
246    $self->{built} = 1;
247   
[1]248    return $self;
249}
250
251sub write {
252    my ($self, $outfile) = @_;
[16]253   
254    # automatically call build if needed to
255    # allow the new->parse->write shortcut
256    $self->build unless $self->{built};
257   
[1]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
[12]267sub write_module {
[16]268    my ($self, $package, $use_tidy) = @_;
[12]269
[32]270    croak '[Text::FormBuilder::write_module] Expecting a package name' unless $package;
[16]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   
[33]280    $Data::Dumper::Terse = 1;           # don't dump $VARn names
281    $Data::Dumper::Quotekeys = 0;       # don't quote simple string keys
[12]282   
[30]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   
[23]287    my %options = (
288        %DEFAULT_OPTIONS,
[24]289        title => $self->{form_spec}{title},
[25]290        text  => $self->{form_spec}{description},
[29]291        fields   => [ map { $$_{name} } @{ $self->{form_spec}{fields} } ],
[24]292        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
[23]293        template => {
294            type => 'Text',
295            engine => {
296                TYPE       => 'STRING',
[30]297                SOURCE     => $self->{build_options}{form_only} ? $self->_form_template : $self->_template($css),
[23]298                DELIMITERS => [ qw(<% %>) ],
299            },
300            data => {
[29]301                sections    => $self->{form_spec}{sections},
[23]302                author      => $self->{form_spec}{author},
303                description => $self->{form_spec}{description},
304            },
305        }, 
306        %{ $self->{build_options} },
307    );
308   
[30]309    # remove our custom options
310    delete $options{$_} foreach qw(form_only css extra_css);
[16]311   
[23]312    my $form_options = keys %options > 0 ? Data::Dumper->Dump([\%options],['*options']) : '';
[16]313   
[12]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
[15]326sub get_form {
[12]327    my \$cgi = shift;
[23]328    my \$cgi_form = CGI::FormBuilder->new(
[12]329        params => \$cgi,
[16]330        $form_options
[12]331    );
332   
333    $field_setup
334   
335    return \$cgi_form;
336}
337
338# module return
3391;
340END
[23]341
[12]342    my $outfile = (split(/::/, $package))[-1] . '.pm';
343   
[16]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 $@;
[33]348        Perl::Tidy::perltidy(source => \$module, destination => $outfile, argv => '-nolq -ci=4');
[16]349    } else {
350        # otherwise, just print as is
[12]351        open FORM, "> $outfile";
352        print FORM $module;
353        close FORM;
354    }
355}
356
[16]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};
[1]363
[16]364    return $self->{form};
365}
366
[12]367sub _form_template {
[33]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>] : '' %>
[15]372<% (grep { $_->{required} } @fields) ? qq[<p id="instructions">(Required fields are marked in <strong>bold</strong>.)</p>] : '' %>
[12]373<% $start %>
[23]374<%
375    # drop in the hidden fields here
376    $OUT = join("\n", map { $$_{field} } grep { $$_{type} eq 'hidden' } @fields);
377%>
378
[29]379<%
380    SECTION: while (my $section = shift @sections) {
[30]381        $OUT .= qq[<table id="] . ($$section{id} || '_default') . qq[">\n];
382        $OUT .= qq[  <caption><h2 class="sectionhead">$$section{head}</h2></caption>] if $$section{head};
[29]383        TABLE_LINE: for my $line (@{ $$section{lines} }) {
384            if ($$line[0] eq 'head') {
[30]385                $OUT .= qq[  <tr><th class="subhead" colspan="2"><h3>$$line[1]</h3></th></tr>\n]
[29]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>];
[30]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                }
[33]400               
401                # mark invalid fields
[29]402                if ($$_{invalid}) {
[30]403                    $OUT .= qq[<td>$$_{field} $$_{comment} Missing or invalid value.</td>];
[29]404                } else {
[30]405                    $OUT .= qq[<td>$$_{field} $$_{comment}</td>];
[29]406                }
[33]407               
[30]408                $OUT .= qq[</tr>\n];
409               
[29]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            }   
[21]424        }
[29]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%>
[12]430  <tr><th></th><td style="padding-top: 1em;"><% $submit %></td></tr>
431</table>
432<% $end %>
433];
434}
435
[33]436sub _pre_template {
[12]437    my $self = shift;
[30]438    my $css = shift || $DEFAULT_CSS;
[33]439    return 
[12]440q[<html>
[1]441<head>
442  <title><% $title %><% $author ? ' - ' . ucfirst $author : '' %></title>
[33]443  <style type="text/css">
444] .
445$css .
446q[  </style>
447  <% $jshead %>
[1]448</head>
449<body>
450
451<h1><% $title %></h1>
452<% $author ? qq[<p id="author">Created by $author</p>] : '' %>
[33]453];
454}
455
456sub _post_template {
457q[<hr />
[1]458<div id="footer">
[16]459  <p id="creator">Made with <a href="http://formbuilder.org/">CGI::FormBuilder</a> version <% CGI::FormBuilder->VERSION %>.</p>
[1]460</div>
461</body>
462</html>
463];
464}
465
[33]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
[7]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}
[1]480
481
482# module return
4831;
484
485=head1 NAME
486
[21]487Text::FormBuilder - Create CGI::FormBuilder objects from simple text descriptions
[1]488
489=head1 SYNOPSIS
490
[16]491    use Text::FormBuilder;
492   
[1]493    my $parser = Text::FormBuilder->new;
494    $parser->parse($src_file);
495   
[16]496    # returns a new CGI::FormBuilder object with
497    # the fields from the input form spec
[7]498    my $form = $parser->form;
[19]499   
500    # write a My::Form module to Form.pm
501    $parser->write_module('My::Form');
[1]502
[23]503=head1 REQUIRES
504
505L<Parse::RecDescent>, L<CGI::FormBuilder>, L<Text::Template>
506
[1]507=head1 DESCRIPTION
508
509=head2 new
510
511=head2 parse
512
[19]513    # parse a file
514    $parser->parse($filename);
[7]515   
[19]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   
[7]525    # or as a class method
[16]526    my $parser = Text::FormBuilder->parse($src_file);
[7]527
528=head2 parse_text
529
[16]530    $parser->parse_text($src);
531
[19]532Parse the given C<$src> text. Returns the parser object.
[16]533
[1]534=head2 build
535
[12]536    $parser->build(%options);
[7]537
[12]538Builds the CGI::FormBuilder object. Options directly used by C<build> are:
539
540=over
541
[19]542=item C<form_only>
[12]543
544Only uses the form portion of the template, and omits the surrounding html,
[19]545title, author, and the standard footer. This does, however, include the
546description as specified with the C<!description> directive.
[12]547
[30]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
[12]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
[16]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
[7]571=head2 form
572
573    my $form = $parser->form;
574
[16]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.
[7]578
[1]579=head2 write
580
[7]581    $parser->write($out_file);
582    # or just print to STDOUT
583    $parser->write;
584
[29]585Calls C<render> on the FormBuilder form, and either writes the resulting
586HTML to a file, or to STDOUT if no filename is given.
[7]587
[29]588CSS Hint: to get multiple sections to all line up their fields, set a
589standard width for th.label
590
[12]591=head2 write_module
592
[16]593    $parser->write_module($package, $use_tidy);
[12]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
[16]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.
[12]601
[16]602First, you parse the formspec and write the module, which you can do as a one-liner:
603
[19]604    $ perl -MText::FormBuilder -e"Text::FormBuilder->parse('formspec.txt')->write_module('My::Form')"
[16]605
606And then, in your CGI script, use the new module:
607
[12]608    #!/usr/bin/perl -w
609    use strict;
610   
611    use CGI;
[19]612    use My::Form;
[12]613   
614    my $q = CGI->new;
[19]615    my $form = My::Form::get_form($q);
[12]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
[16]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
[19]628    # write tidier code
629    $parser->write_module('My::Form', 1);
630
[7]631=head2 dump
632
[16]633Uses L<YAML> to print out a human-readable representation of the parsed
[7]634form spec.
635
[33]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
[1]649=head1 LANGUAGE
650
[19]651    field_name[size]|descriptive label[hint]:type=default{option1[display string],...}//validate
[1]652   
653    !title ...
654   
[12]655    !author ...
656   
[16]657    !description {
658        ...
659    }
660   
[1]661    !pattern name /regular expression/
[16]662   
[1]663    !list name {
[7]664        option1[display string],
665        option2[display string],
[1]666        ...
667    }
[12]668   
669    !list name &{ CODE }
670   
[29]671    !section id heading
672   
[12]673    !head ...
[1]674
675=head2 Directives
676
677=over
678
679=item C<!pattern>
680
[12]681Defines a validation pattern.
682
[1]683=item C<!list>
684
[12]685Defines a list for use in a C<radio>, C<checkbox>, or C<select> field.
686
[1]687=item C<!title>
688
[7]689=item C<!author>
690
[16]691=item C<!description>
692
[19]693A brief description of the form. Suitable for special instructions on how to
694fill out the form.
695
[29]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
[12]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
[1]707=back
708
709=head2 Fields
710
[24]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:
[1]715
[24]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
[19]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
[24]739The descriptive label can be a multiword string, as described above.
[19]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
[23]749    password
750    file
751    checkbox
752    radio
[19]753    select
[23]754    hidden
[19]755    static
756
[21]757To change the size of the input field, add a bracketed subscript after the
758field name (but before the descriptive label):
[19]759
[21]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
[24]771Values are in a comma-separated list of single words or multiword strings
772inside curly braces. Whitespace between values is irrelevant.
[21]773
[26]774To add more descriptive display text to a value in a list, add a square-bracketed
[19]775``subscript,'' as in:
776
777    ...:select{red[Scarlet],blue[Azure],green[Olive Drab]}
778
[1]779If you have a list of options that is too long to fit comfortably on one line,
[26]780you should use the C<!list> directive:
[1]781
[19]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
[21]797list, as the example does, or the fancier C<< ( { value1 => 'Description 1'},
798{ value2 => 'Description 2}, ... ) >> form.
[19]799
[24]800I<B<NOTE:> This feature of the language may go away unless I find a compelling
[19]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
[24]803enough with the CGI::FormBuilder object directly.>
[19]804
[26]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
[30]811In this case, the label ``I want to recieve more information'' will be
812printed to the right of the checkbox.
[26]813
[19]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
[24]819Default values can also be either single words or multiword strings.
820
[19]821To validate a field, include a validation type at the end of the field line:
822
823    email|Email address//EMAIL
824
[21]825Valid validation types include any of the builtin defaults from L<CGI::FormBuilder>,
[19]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
[24]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
[1]845=head2 Comments
846
847    # comment ...
848
849Any line beginning with a C<#> is considered a comment.
850
[7]851=head1 TODO
852
[31]853Allow for custom wrappers around the C<form_template>
854
[33]855Use the custom message file format for messages in the built in template (i18n/l10n)
[23]856
[30]857Maybe use HTML::Template instead of Text::Template for the built in template
[28]858(since CGI::FormBuilder users may be more likely to already have HTML::Template)
859
[23]860Better examples in the docs (maybe a standalone or two as well)
861
862Document the defaults that are passed to CGI::FormBuilder
863
[16]864C<!include> directive to include external formspec files
[7]865
[19]866Better tests!
[16]867
[23]868=head1 BUGS
869
[30]870I'm sure they're in there, I just haven't tripped over any new ones lately. :-)
[26]871
[1]872=head1 SEE ALSO
873
874L<CGI::FormBuilder>
875
[23]876=head1 THANKS
877
[26]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
[29]880sections.
[23]881
[16]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
[1]893=cut
Note: See TracBrowser for help on using the repository browser.