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

Last change on this file since 24 was 24, checked in by peter, 20 years ago

allow for validating but not required fields

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