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

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

updated docs and version number

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