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

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

allow for validating but not required fields

File size: 20.9 KB
Line 
1package Text::FormBuilder;
2
3use strict;
4use warnings;
5
6use vars qw($VERSION);
7
8$VERSION = '0.06';
9
10use Carp;
11use Text::FormBuilder::Parser;
12use CGI::FormBuilder;
13
14# the default options passed to CGI::FormBuilder->new
15my %DEFAULT_OPTIONS = (
16    method => 'GET',
17    javascript => 0,
18    keepextras => 1,
19);
20
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 {
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 {
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) = @_;
55   
56    # so it can be called as a class method
57    $self = $self->new unless ref $self;
58   
59    $self->{form_spec} = $self->{parser}->form_spec($src);
60   
61    # mark structures as not built (newly parsed text)
62    $self->{built} = 0;
63   
64    return $self;
65}
66
67sub build {
68    my ($self, %options) = @_;
69
70    # save the build options so they can be used from write_module
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   
78    # substitute in custom pattern definitions for field validation
79    if (my %patterns = %{ $self->{form_spec}{patterns} || {} }) {
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    }
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    }
107   
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   
118    # substitute in list names
119    if (my %lists = %{ $self->{form_spec}{lists} || {} }) {
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    }
135   
136   
137    # TODO: configurable threshold for this
138    foreach (@{ $self->{form_spec}{fields} }) {
139        $$_{ulist} = 1 if defined $$_{options} and @{ $$_{options} } >= 3;
140    }
141   
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} };
151
152   
153    $self->{form} = CGI::FormBuilder->new(
154        %DEFAULT_OPTIONS,
155        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
156        title => $self->{form_spec}{title},
157        template => {
158            type => 'Text',
159            engine => {
160                TYPE       => 'STRING',
161                SOURCE     => $form_only ? $self->_form_template : $self->_template,
162                DELIMITERS => [ qw(<% %>) ],
163            },
164            data => {
165                lines       => $self->{form_spec}{lines},
166                headings    => $self->{form_spec}{headings},
167                author      => $self->{form_spec}{author},
168                description => $self->{form_spec}{description},
169            },
170        },
171        %options,
172    );
173    $self->{form}->field(%{ $_ }) foreach @{ $self->{form_spec}{fields} };
174   
175    # mark structures as built
176    $self->{built} = 1;
177   
178    return $self;
179}
180
181sub write {
182    my ($self, $outfile) = @_;
183   
184    # automatically call build if needed to
185    # allow the new->parse->write shortcut
186    $self->build unless $self->{built};
187   
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
197sub write_module {
198    my ($self, $package, $use_tidy) = @_;
199
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   
210    # don't dump $VARn names
211    $Data::Dumper::Terse = 1;
212   
213    my $title       = $self->{form_spec}{title} || '';
214    my $author      = $self->{form_spec}{author} || '';
215    my $description = $self->{form_spec}{description} || '';
216   
217    my $headings    = Data::Dumper->Dump([$self->{form_spec}{headings}],['headings']);
218    my $lines       = Data::Dumper->Dump([$self->{form_spec}{lines}],['lines']);
219    my $fields      = Data::Dumper->Dump([ [ map { $$_{name} } @{ $self->{form_spec}{fields} } ] ],['fields']);
220   
221    my %options = (
222        %DEFAULT_OPTIONS,
223        title => $self->{form_spec}{title},
224        required => [ map { $$_{name} } grep { $$_{required} } @{ $self->{form_spec}{fields} } ],
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   
242    my $source = $options{form_only} ? $self->_form_template : $self->_template;
243   
244    delete $options{form_only};
245   
246    my $form_options = keys %options > 0 ? Data::Dumper->Dump([\%options],['*options']) : '';
247   
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
260sub get_form {
261    my \$cgi = shift;
262    my \$cgi_form = CGI::FormBuilder->new(
263        params => \$cgi,
264        $form_options
265    );
266   
267    $field_setup
268   
269    return \$cgi_form;
270}
271
272# module return
2731;
274END
275
276    my $outfile = (split(/::/, $package))[-1] . '.pm';
277   
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
285        open FORM, "> $outfile";
286        print FORM $module;
287        close FORM;
288    }
289}
290
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};
297
298    return $self->{form};
299}
300
301sub _form_template {
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>] : '' %>
304<% $start %>
305<%
306    # drop in the hidden fields here
307    $OUT = join("\n", map { $$_{field} } grep { $$_{type} eq 'hidden' } @fields);
308%>
309
310<table>
311
312<% TABLE_LINE: for my $line (@lines) {
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}};
319        # skip hidden fields in the table
320        next TABLE_LINE if $$_{type} eq 'hidden';
321       
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
348} %>
349  <tr><th></th><td style="padding-top: 1em;"><% $submit %></td></tr>
350</table>
351<% $end %>
352];
353}
354
355sub _template {
356    my $self = shift;
357q[<html>
358<head>
359  <title><% $title %><% $author ? ' - ' . ucfirst $author : '' %></title>
360  <style type="text/css">
361    #author, #footer { font-style: italic; }
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; }
365    td ul { list-style: none; padding-left: 0; margin-left: 0; }
366    .sublabel { color: #999; }
367    .invalid { background: red; }
368  </style>
369</head>
370<body>
371
372<h1><% $title %></h1>
373<% $author ? qq[<p id="author">Created by $author</p>] : '' %>
374] . $self->_form_template . q[
375<hr />
376<div id="footer">
377  <p id="creator">Made with <a href="http://formbuilder.org/">CGI::FormBuilder</a> version <% CGI::FormBuilder->VERSION %>.</p>
378</div>
379</body>
380</html>
381];
382}
383
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}
392
393
394# module return
3951;
396
397=head1 NAME
398
399Text::FormBuilder - Create CGI::FormBuilder objects from simple text descriptions
400
401=head1 SYNOPSIS
402
403    use Text::FormBuilder;
404   
405    my $parser = Text::FormBuilder->new;
406    $parser->parse($src_file);
407   
408    # returns a new CGI::FormBuilder object with
409    # the fields from the input form spec
410    my $form = $parser->form;
411   
412    # write a My::Form module to Form.pm
413    $parser->write_module('My::Form');
414
415=head1 REQUIRES
416
417L<Parse::RecDescent>, L<CGI::FormBuilder>, L<Text::Template>
418
419=head1 DESCRIPTION
420
421=head2 new
422
423=head2 parse
424
425    # parse a file
426    $parser->parse($filename);
427   
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   
437    # or as a class method
438    my $parser = Text::FormBuilder->parse($src_file);
439
440=head2 parse_text
441
442    $parser->parse_text($src);
443
444Parse the given C<$src> text. Returns the parser object.
445
446=head2 build
447
448    $parser->build(%options);
449
450Builds the CGI::FormBuilder object. Options directly used by C<build> are:
451
452=over
453
454=item C<form_only>
455
456Only uses the form portion of the template, and omits the surrounding html,
457title, author, and the standard footer. This does, however, include the
458description as specified with the C<!description> directive.
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
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
475=head2 form
476
477    my $form = $parser->form;
478
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.
482
483=head2 write
484
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
492=head2 write_module
493
494    $parser->write_module($package, $use_tidy);
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
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.
502
503First, you parse the formspec and write the module, which you can do as a one-liner:
504
505    $ perl -MText::FormBuilder -e"Text::FormBuilder->parse('formspec.txt')->write_module('My::Form')"
506
507And then, in your CGI script, use the new module:
508
509    #!/usr/bin/perl -w
510    use strict;
511   
512    use CGI;
513    use My::Form;
514   
515    my $q = CGI->new;
516    my $form = My::Form::get_form($q);
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
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
529    # write tidier code
530    $parser->write_module('My::Form', 1);
531
532=head2 dump
533
534Uses L<YAML> to print out a human-readable representation of the parsed
535form spec.
536
537=head1 LANGUAGE
538
539    field_name[size]|descriptive label[hint]:type=default{option1[display string],...}//validate
540   
541    !title ...
542   
543    !author ...
544   
545    !description {
546        ...
547    }
548   
549    !pattern name /regular expression/
550   
551    !list name {
552        option1[display string],
553        option2[display string],
554        ...
555    }
556   
557    !list name &{ CODE }
558   
559    !head ...
560
561=head2 Directives
562
563=over
564
565=item C<!pattern>
566
567Defines a validation pattern.
568
569=item C<!list>
570
571Defines a list for use in a C<radio>, C<checkbox>, or C<select> field.
572
573=item C<!title>
574
575=item C<!author>
576
577=item C<!description>
578
579A brief description of the form. Suitable for special instructions on how to
580fill out the form.
581
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
588=back
589
590=head2 Fields
591
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:
596
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
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
620The descriptive label can be a multiword string, as described above.
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
630    password
631    file
632    checkbox
633    radio
634    select
635    hidden
636    static
637
638To change the size of the input field, add a bracketed subscript after the
639field name (but before the descriptive label):
640
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
652Values are in a comma-separated list of single words or multiword strings
653inside curly braces. Whitespace between values is irrelevant.
654
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
660If you have a list of options that is too long to fit comfortably on one line,
661consider using the C<!list> directive:
662
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
678list, as the example does, or the fancier C<< ( { value1 => 'Description 1'},
679{ value2 => 'Description 2}, ... ) >> form.
680
681I<B<NOTE:> This feature of the language may go away unless I find a compelling
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
684enough with the CGI::FormBuilder object directly.>
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
691Default values can also be either single words or multiword strings.
692
693To validate a field, include a validation type at the end of the field line:
694
695    email|Email address//EMAIL
696
697Valid validation types include any of the builtin defaults from L<CGI::FormBuilder>,
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
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
717=head2 Comments
718
719    # comment ...
720
721Any line beginning with a C<#> is considered a comment.
722
723=head1 TODO
724
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
736C<!include> directive to include external formspec files
737
738Better tests!
739
740=head1 BUGS
741
742=head1 SEE ALSO
743
744L<CGI::FormBuilder>
745
746=head1 THANKS
747
748Thanks to eszpee for pointing out some bugs in the default value parsing.
749
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
761=cut
Note: See TracBrowser for help on using the repository browser.