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

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

marked Parse::RecDescent as an explicit dependency
added a single-quoted string to the grammar that can be
used in the labels and default values to include characters in [\w\t ]

generated code leaves out overwrriten options

allow option lists to have simple multiword and quoted string values

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