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

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

fixed errors from undefined references
removed old field/heading code from grammar

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