.\" Automatically generated by Pod::Man version 1.15
.\" Thu Jan 29 11:04:55 2004
.\"
.\" Standard preamble:
.\" ======================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used
.\" to do unbreakable dashes and therefore won't be available. \*(C` and
.\" \*(C' expand to `' in nroff, nothing in troff, for use with C<>
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr
.\" for titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and
.\" index entries marked with X<> in POD. Of course, you'll have to process
.\" the output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it
.\" makes way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
.bd B 3
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ======================================================================
.\"
.IX Title "FORMBUILDER 1"
.TH FORMBUILDER 1 "perl v5.6.1" "2003-09-20" "User Contributed Perl Documentation"
.UC
.SH "NAME"
\&\s-1CGI:\s0:FormBuilder \- Easily generate and process stateful forms
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& use CGI::FormBuilder;
.Ve
.Vb 2
\& # Let's assume we did a DBI query to get existing values
\& my $dbval = $sth->fetchrow_hashref;
.Ve
.Vb 8
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/name email phone gender/],
\& values => $dbval,
\& validate => { email => 'EMAIL', phone => 'PHONE' },
\& required => 'ALL',
\& font => 'arial,helvetica',
\& );
.Ve
.Vb 2
\& # Change gender field to have options
\& $form->field(name => 'gender', options => [qw/Male Female/]);
.Ve
.Vb 2
\& if ($form->submitted && $form->validate) {
\& my $fields = $form->field; # get form fields as hashref
.Ve
.Vb 3
\& # Do something to update your data (you would write this)
\& do_data_update($fields->{name}, $fields->{email},
\& $fields->{phone}, $fields->{gender});
.Ve
.Vb 2
\& # Show confirmation screen
\& print $form->confirm(header => 1);
.Ve
.Vb 2
\& # Email the person a brief confirmation
\& $form->mailconfirm(to => $fields->{email});
.Ve
.Vb 4
\& } else {
\& # Print out the form
\& print $form->render(header => 1);
\& }
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This documentation is very extensive, and likely all you will need.
However, there is even more online, as well as examples and tutorials,
at:
.PP
.Vb 1
\& www.formbuilder.org
.Ve
You should also consider joining the mailing list by sending an email to:
.PP
.Vb 1
\& fbusers-subscribe@formbuilder.org
.Ve
You are encouraged to visit the website, even if you are a longtime user,
as there are a number of hints and tricks that you may find useful.
.Sh "Overview"
.IX Subsection "Overview"
I hate generating and processing forms. Hate it, hate it, hate it,
hate it. My forms almost always end up looking the same, and almost
always end up doing the same thing. Unfortunately, there really haven't
been any tools out there that streamline the process. Many modules
simply substitute Perl for \s-1HTML\s0 code:
.PP
.Vb 2
\& # The manual way
\& print qq();
.Ve
.Vb 2
\& # The module way
\& print input(-name => 'email', -type => 'text', -size => '20');
.Ve
The problem is, that doesn't really gain you anything. You still
have just as much code. Modules like the venerable \f(CW\*(C`CGI.pm\*(C'\fR are great
for processing parameters, but they don't save you much time when
trying to generate and process forms.
.PP
The goal of \f(CW\*(C`CGI::FormBuilder\*(C'\fR (\fBFormBuilder\fR) is to provide an easy way
for you to generate and process \s-1CGI\s0 form-based applications. This module
is designed to be smart in that it figures a lot of stuff out for you.
As a result, \fBFormBuilder\fR gives you about a \fB4:1\fR ratio of the code
it generates versus what you have to write.
.PP
For example, if you have multiple values for a field, it sticks them
in a radio, checkbox, or select group, depending on some factors. It
will also automatically name fields for you in human-readable labels
depending on the field names, and lay everything out in a nicely
formatted table. It will even title the form based on the name of
the script itself (\f(CW\*(C`order_form.cgi\*(C'\fR becomes \*(L"Order Form\*(R").
.PP
Plus, \fBFormBuilder\fR provides you full-blown validation for your
fields, including some useful builtin patterns. It will even generate
JavaScript validation routines on the fly! And, of course, it
maintains state (\*(L"stickiness\*(R") across submissions, with hooks
provided for you to plugin your own sessionid module such
as \f(CW\*(C`Apache::Session\*(C'\fR.
.PP
And though it's smart, it allows you to customize it as well. For
example, if you really want something to be a checkbox, you can make
it a checkbox. And, if you really want something to be output a
specific way, you can even specify the name of an \f(CW\*(C`HTML::Template\*(C'\fR or
Template Toolkit (\f(CW\*(C`Template\*(C'\fR) compatible template which will be
automatically filled in, statefully.
.Sh "Walkthrough"
.IX Subsection "Walkthrough"
Let's walk through a whole example to see how \fBFormBuilder\fR works.
The basic usage is straightforward, and has these steps:
.Ip "1." 4
Create a new \f(CW\*(C`CGI::FormBuilder\*(C'\fR object with the proper options
.Ip "2." 4
Modify any fields that may need fiddling with
.Ip "3." 4
Validate the form, if applicable, and print it out
.PP
\&\fBFormBuilder\fR is designed to do the tedious grunt work for you.
In fact, a whole form-based application can be output with nothing
more than this:
.PP
.Vb 1
\& use CGI::FormBuilder;
.Ve
.Vb 1
\& my @fields = qw(name email password confirm_password zipcode);
.Ve
.Vb 1
\& my $form = CGI::FormBuilder->new(fields => \e@fields);
.Ve
.Vb 1
\& print $form->render(header => 1);
.Ve
Not only does this generate about 4 times as much HTML-compliant code
as the above Perl code, but it also keeps values statefully across
submissions, even when multiple values are selected. And if you
do nothing more than add the \f(CW\*(C`validate\*(C'\fR option to \f(CW\*(C`new()\*(C'\fR:
.PP
.Vb 4
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& validate => {email => 'EMAIL'}
\& );
.Ve
You now get a whole set of JavaScript validation code, as well
as Perl hooks for validation. In total you get about \fB6 times\fR
the amount of code generated versus written. Plus, statefulness
and validation are handled for you, automatically.
.PP
Let's keep building on this example. Say we decide that we really
like our form fields and their stickiness, but we need to change
a couple things. For one, we want the page to be laid out very
precisely. No problem! We simply create an \f(CW\*(C`HTML::Template\*(C'\fR compatible
template and tell our module to use that. The \f(CW\*(C`HTML::Template\*(C'\fR
module uses special \s-1HTML\s0 tags to print out variables. All you
have to do in your template is create one for each field that you're
printing, as well as one for the form header itself:
.PP
.Vb 17
\&
\&
\&
\&
\&
\&
\&
User Information
\& Please fill out the following information:
\&
\&
Your full name:
\&
Your email address:
\&
Choose a password:
\&
Please confirm it:
\&
Your home zipcode:
\&
\&
\&
.Ve
Then, all you need to do in your Perl is add the \f(CW\*(C`template\*(C'\fR option:
.PP
.Vb 3
\& my $form = CGI::FormBuilder->new(fields => \e@fields,
\& validate => {email => 'EMAIL'},
\& template => 'userinfo.tmpl');
.Ve
And the rest of the code stays the same.
.PP
You can also do a similar thing using the Template Toolkit
(http://template-toolkit.org/) to generate the form. This time,
specify the \f(CW\*(C`template\*(C'\fR option as a hashref which includes the
\&\f(CW\*(C`type\*(C'\fR option set to \f(CW\*(C`TT2\*(C'\fR and the \f(CW\*(C`template\*(C'\fR option to denote
the name of the template you want processed. You can also add
\&\f(CW\*(C`variable\*(C'\fR as an option (among others) to denote the variable
name that you want the form data to be referenced by.
.PP
.Vb 8
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'TT2',
\& template => 'userinfo.tmpl',
\& variable => 'form',
\& }
\& );
.Ve
The template might look something like this:
.PP
.Vb 21
\&
\&
\& [% form.title %]
\& [% form.jshead %]
\&
\&
\& [% form.start %]
\&
\& [% IF field.invalid %]
\& Missing or invalid entry, please try again.
\&
\& [% END %]
.Ve
.Vb 13
\& [% field.field %]
\&
\&
\& [% END %]
\&
\&
\& [% form.submit %]
\&
\&
\&
\& [% form.end %]
\&
\&
.Ve
So, as you can see, there is plugin capability for \fBFormBuilder\fR
to basically \*(L"run\*(R" the two major templating engines, \fB\s-1HTML:\s0:Template\fR
and \fBTemplate Toolkit\fR.
.PP
Now, back to \fBFormBuilder\fR. Let's assume that we want to validate our
form on the server side, which is common since the user may not be running
JavaScript. All we have to add is the statement:
.PP
.Vb 1
\& $form->validate;
.Ve
Which will go through the form, checking each value specified to
the validate option to see if it's ok. If there's a problem, then
that field is highlighted so that when you print it out the errors
will be apparent.
.PP
Of course, the above returns a truth value, which we should use
to see if the form was valid. That way, we can only fiddle our
database or whatever if everything looks good. We can then use
our \f(CW\*(C`confirm()\*(C'\fR method to print out a generic results page:
.PP
.Vb 6
\& if ($form->validate) {
\& # form was good, let's update database ...
\& print $form->confirm;
\& } else {
\& print $form->render;
\& }
.Ve
The \f(CW\*(C`validate()\*(C'\fR method will use whatever criteria were passed
into \f(CW\*(C`new()\*(C'\fR via the \f(CW\*(C`validate\*(C'\fR parameter to check the form
submission to make sure it's correct.
.PP
However, we really only want to do this after our form has been
submitted, since this could otherwise result in our form showing
errors even though the user hasn't gotten a chance to fill it
out yet. As such, we can check for whether the form has been
submitted yet by wrapping the above with:
.PP
.Vb 6
\& if ($form->submitted && $form->validate) {
\& # form was good, let's update database ...
\& print $form->confirm;
\& } else {
\& print $form->render;
\& }
.Ve
Of course, this module wouldn't be really smart if it didn't provide
some more stuff for you. A lot of times, we want to send a simple
confirmation email to the user (and maybe ourselves) saying that
the form has been submitted. Just use \f(CW\*(C`mailconfirm()\*(C'\fR:
.PP
.Vb 2
\& $form->mailconfirm(to => $form->field('email'),
\& from => 'auto-reply');
.Ve
With \fBFormBuilder\fR, any default values you specify are automatically
overridden by whatever the user enters into the form and submits.
These can then be gotten to by using the \f(CW\*(C`field()\*(C'\fR method:
.PP
.Vb 1
\& my $email = $form->field(name => 'email');
.Ve
Of course, like \f(CW\*(C`CGI.pm's param()\*(C'\fR you can just specify the name
of the field when getting a value back:
.PP
.Vb 1
\& my $email = $form->field('email');
.Ve
\&\fBFormBuilder\fR is good at giving you the data that you should
be getting. That is, let's say that you initially setup your
\&\f(CW\*(C`$form\*(C'\fR object to use a hash of existing values from a database
select or something. Then, you \f(CW\*(C`render()\*(C'\fR the form, the user
fills it out, and submits it. When you call \f(CW\*(C`field()\*(C'\fR, you'll
get whatever the correct value is, either the default or what
the user entered across the \s-1CGI\s0.
.PP
So, our complete code thus far looks like this:
.PP
.Vb 1
\& use CGI::FormBuilder;
.Ve
.Vb 1
\& my @fields = qw(name email password confirm_password zipcode);
.Ve
.Vb 6
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& validate => { email => 'EMAIL' },
\& template => 'userinfo.tmpl',
\& header => 1
\& );
.Ve
.Vb 4
\& if ($form->submitted && $form->validate) {
\& # form was ok, let's update database (you write this part)
\& my $fields = $form->field; # get all fields as hashref
\& do_data_update($fields);
.Ve
.Vb 2
\& # show a confirmation message
\& print $form->confirm;
.Ve
.Vb 7
\& # and send them email about their submission
\& $form->mailconfirm(to => $form->field('email'),
\& from => 'auto-reply');
\& } else {
\& # print the form for them to fill out
\& print $form->render;
\& }
.Ve
You may be surprised to learn that for many applications, the
above is probably all you'll need. Just fill in the parts that
affect what you want to do (like the database code), and you're
on your way.
.SH "REFERENCES"
.IX Header "REFERENCES"
This really doesn't belong here, but unfortunately many people are
confused by references in Perl. Don't be \- they're not that tricky.
When you take a reference, you're basically turning something into
a scalar value. Sort of. You have to do this if you want to pass
arrays intact into functions in Perl 5.
.PP
A reference is taken by preceding the variable with a backslash (\e).
In our examples above, you saw something similar to this:
.PP
.Vb 1
\& my @fields = ('name', 'email'); # same as = qw(name email)
.Ve
.Vb 1
\& my $form = CGI::FormBuilder->new(fields => \e@fields);
.Ve
Here, \f(CW\*(C`\e@fields\*(C'\fR is a reference. Specifically, it's an array
reference, or \*(L"arrayref\*(R" for short.
.PP
Similarly, we can do the same thing with hashes:
.PP
.Vb 4
\& my %validate = (
\& name => 'NAME';
\& email => 'EMAIL',
\& );
.Ve
.Vb 1
\& my $form = CGI::FormBuilder->new( ... validate => \e%validate);
.Ve
Here, \f(CW\*(C`\e%validate\*(C'\fR is a hash reference, or \*(L"hashref\*(R".
.PP
Basically, if you don't understand references and are having trouble
wrapping your brain around them, you can try this simple rule: Any time
you're passing an array or hash into a function, you must precede it
with a backslash. Usually that's true for \s-1CPAN\s0 modules.
.PP
Finally, there are two more types of references: anonymous arrayrefs
and anonymous hashrefs. These are created with \f(CW\*(C`[]\*(C'\fR and \f(CW\*(C`{}\*(C'\fR,
respectively. So, for our purposes there is no real difference between
this code:
.PP
.Vb 2
\& my @fields = qw(name email);
\& my %validate = (name => 'NAME', email => 'EMAIL');
.Ve
.Vb 4
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& validate => \e%validate
\& );
.Ve
And this code:
.PP
.Vb 4
\& my $form = CGI::FormBuilder->new(
\& fields => [ qw(name email) ],
\& validate => { name => 'NAME', email => 'EMAIL' }
\& );
.Ve
Except that the latter doesn't require that we first create
\&\f(CW\*(C`@fields\*(C'\fR and \f(CW\*(C`%validate\*(C'\fR variables.
.PP
Now back to our regularly-scheduled program...
.SH "FUNCTIONS"
.IX Header "FUNCTIONS"
Of course, in the spirit of flexibility this module takes a bizillion
different options. None of these are mandatory \- you can call the
\&\f(CW\*(C`new()\*(C'\fR constructor without any fields, but your form will be really
really short. :\-)
.PP
This documentation is very extensive, but can be a bit dizzying due
to the enormous number of options that let you tweak just about anything.
As such, I recommend that if this is your first time using this module,
you stop and visit:
.PP
.Vb 1
\& www.formbuilder.org
.Ve
And click on \*(L"Tutorials\*(R" and \*(L"Examples\*(R". Then, use the following section
as a reference later on.
.Sh "\fInew()\fP"
.IX Subsection "new()"
This is the constructor, and must be called very first. It returns
a \f(CW\*(C`$form\*(C'\fR object, which you can then modify and print out to create
the form. This function accepts all of the options listed under \f(CW\*(C`render()\*(C'\fR
below. In addition, it takes 6 options that can only be specified to \f(CW\*(C`new()\*(C'\fR:
.Ip "fields => \e@array | \e%hash" 4
.IX Item "fields => @array | %hash"
The \f(CW\*(C`fields\*(C'\fR option takes an arrayref of fields to use in the form.
The fields will be printed out in the same order they are specified.
This option is needed if you expect your form to have any fields,
and is \fIthe\fR central option to FormBuilder.
.Sp
You can also specify a hashref of key/value pairs. The advantage is
you can then bypass the \f(CW\*(C`values\*(C'\fR option. However, the big disadvantage
is you cannot control the order of the fields. This is ok if you're
using a template, but in real-life it turns out that passing a hashref
to \f(CW\*(C`fields\*(C'\fR is not very useful.
.Ip "name => \f(CW$string\fR" 4
.IX Item "name => $string"
This option can \fBonly\fR be specified to \f(CW\*(C`new()\*(C'\fR but not to \f(CW\*(C`render()\*(C'\fR.
.Sp
This names the form. It is optional, but if you specify it you must
do so in \f(CW\*(C`new()\*(C'\fR since the name is then used to alter how variables
are created and looked up.
.Sp
This option has an important side effect. When used, it renames several
key variables and functions according to the name of the form. This
allows you to (a) use multiple forms in a sequential application and
(b) display multiple forms inline in one document. If you're trying
to build a complex multi-form app and are having problems, try naming
your forms.
.Ip "params => \f(CW$object\fR" 4
.IX Item "params => $object"
This specifies an object from which the parameters should be derived.
The object must have a \f(CW\*(C`param()\*(C'\fR method which will return values
for each parameter by name. By default a \s-1CGI\s0 object will be
automatically created and used.
.Sp
However, you will want to specify this if you're using \f(CW\*(C`mod_perl\*(C'\fR:
.Sp
.Vb 2
\& use Apache::Request;
\& use CGI::FormBuilder;
.Ve
.Vb 6
\& sub handler {
\& my $r = Apache::Request->new(shift);
\& my $form = CGI::FormBuilder->new(... params => $r);
\& # ...
\& print $form->render;
\& }
.Ve
Or, if you need to initialize a \f(CW\*(C`CGI.pm\*(C'\fR object separately and
are using a \f(CW\*(C`POST\*(C'\fR form method:
.Sp
.Vb 2
\& use CGI;
\& use CGI::FormBuilder;
.Ve
.Vb 4
\& my $q = new CGI;
\& my $mode = $q->param('mode');
\& # do stuff based on mode ...
\& my $form = CGI::FormBuilder->new(... params => $q);
.Ve
The above example would allow you to access \s-1CGI\s0 parameters
directly via \f(CW\*(C`$q\->param\*(C'\fR (however, note that you could
get the same functionality by using \f(CW\*(C`$form\->cgi_param\*(C'\fR).
.Ip "validate => \e%hash" 4
.IX Item "validate => %hash"
This option takes a hashref of key/value pairs. Each key is the
name of a field from the \f(CW\*(C`fields\*(C'\fR option, or the string \f(CW\*(C`ALL\*(C'\fR
in which case it applies to all fields. Each value is one of
the following:
.Sp
.Vb 6
\& - a regular expression to match the field against
\& - an arrayref of values of which the field must be one
\& - a string that corresponds to one of the builtin patterns
\& - a string containing a literal code comparison to do
\& - a reference to a sub to be used to validate the field
\& (the sub will receive the value to check as the first arg)
.Ve
In addition, each of these can also be grouped together as:
.Sp
.Vb 2
\& - a hashref containing pairings of comparisons to do for
\& the two different languages, "javascript" and "perl"
.Ve
By default, the \f(CW\*(C`validate\*(C'\fR option also sets up each field so that
it is required. However, if you specify the \f(CW\*(C`required\*(C'\fR option, then
only those fields explicitly listed would be required, and the rest
would only be validated if filled in. See the \f(CW\*(C`required\*(C'\fR option for
more details.
.Sp
Let's look at a concrete example:
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(
.Ve
.Vb 2
\& fields => [qw/username password confirm_password
\& first_name last_name email/],
.Ve
.Vb 11
\& validate => { username => [qw/nate jim bob/],
\& first_name => '/^\ew+$/', # note the
\& last_name => '/^\ew+$/', # single quotes!
\& email => 'EMAIL',
\& password => \e&check_password,
\& confirm_password => {
\& javascript => '== form.password.value',
\& perl => 'eq $form->field("password")'
\& }
\& }
\& );
.Ve
.Vb 8
\& # simple sub example to check the password
\& sub check_password ($) {
\& my $v = shift; # first arg is value
\& return unless $v =~ /^.{6,8}/; # 6-8 chars
\& return if $v eq "password"; # dummy check
\& return unless passes_crack($v); # you write "passes_crack()"
\& return 1;
\& }
.Ve
This would create both JavaScript and Perl conditionals on the fly
that would ensure:
.Sp
.Vb 6
\& - "username" was either "nate", "jim", or "bob"
\& - "first_name" and "last_name" both match the regex's specified
\& - "email" is a valid EMAIL format
\& - "password" passes the checks done by check_password(), meaning
\& that the sub returns true
\& - "confirm_password" is equal to the "password" field
.Ve
\&\fBAny regular expressions you specify must be enclosed in single quotes
because they need to be used in both JavaScript and Perl code.\fR As
such, specifying a \f(CW\*(C`qr//\*(C'\fR will \s-1NOT\s0 work.
.Sp
Note that for both the \f(CW\*(C`javascript\*(C'\fR and \f(CW\*(C`perl\*(C'\fR hashref code options,
the form will be present as the variable named \f(CW\*(C`form\*(C'\fR. For the Perl
code, you actually get a complete \f(CW\*(C`$form\*(C'\fR object meaning that you
have full access to all its methods (although the \f(CW\*(C`field()\*(C'\fR method
is probably the only one you'll need for validation).
.Sp
In addition to taking any regular expression you'd like, the
\&\f(CW\*(C`validate\*(C'\fR option also has many builtin defaults that can
prove helpful:
.Sp
.Vb 27
\& VALUE - is any type of non-null value
\& WORD - is a word (\ew+)
\& NAME - matches [a-zA-Z] only
\& FNAME - person's first name, like "Jim" or "Joe-Bob"
\& LNAME - person's last name, like "Smith" or "King, Jr."
\& NUM - number, decimal or integer
\& INT - integer
\& FLOAT - floating-point number
\& PHONE - phone number in form "123-456-7890" or "(123) 456-7890"
\& INTPHONE- international phone number in form "+prefix local-number"
\& EMAIL - email addr in form "name@host.domain"
\& CARD - credit card, including Amex, with or without -'s
\& DATE - date in format MM/DD/YYYY or DD/MM/YYYY
\& MMYY - date in format MM/YY or MMYY
\& MMYYYY - date in format MM/YYYY or MMYYYY
\& CCMM - strict checking for valid credit card 2-digit month ([0-9]|1[012])
\& CCYY - valid credit card 2-digit year
\& ZIPCODE - US postal code in format 12345 or 12345-6789
\& STATE - valid two-letter state in all uppercase
\& IPV4 - valid IPv4 address
\& NETMASK - valid IPv4 netmask
\& FILE - UNIX format filename (/usr/bin)
\& WINFILE - Windows format filename (C:\ewindows\esystem)
\& MACFILE - MacOS format filename (folder:subfolder:subfolder)
\& HOST - valid hostname (some-name)
\& DOMAIN - valid domainname (www.i-love-bacon.com)
\& ETHER - valid ethernet address using either : or . as separators
.Ve
I know some of the above are US-centric, but then again that's where I live. :\-)
So if you need different processing just create your own regular expression
and pass it in. If there's something really useful let me know and maybe
I'll add it.
.Ip "messages => \f(CW$filename\fR | \e%hash" 4
.IX Item "messages => $filename | %hash"
This option allows you to customize basically all the messages
this module outputs. This is useful if you are writing a multilingual
application, or are just anal and want the messages exactly right.
.Sp
The messaging system is simple, as it borrows somewhat from \f(CW\*(C`getttext()\*(C'\fR.
Each message displayed is given a unique key. If you specify a custom
message for a given key, then that message is used. Otherwise, the
default is printed. Note that it is up to you to figure out what to
pass in \- there is no magic \f(CW\*(C`LC_MESSAGES\*(C'\fR mysterium to this module.
.Sp
For example, let's say you wrote a script that needed to display custom
JavaScript error messages. You could do something like this:
.Sp
.Vb 2
\& # Get language requested
\& my $lang = $ENV{HTTP_ACCEPT_LANGUAGE} || 'en';
.Ve
.Vb 2
\& # Get the appropriate file
\& my $langfile = "/languages/formbuilder/messages.$lang";
.Ve
.Vb 4
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& messages => $langfile,
\& );
.Ve
.Vb 1
\& print $form->render;
.Ve
Then, your language file would contain the following:
.Sp
.Vb 4
\& # FormBuilder messages for "en" locale
\& js_invalid_start %s error(s) were found in your form:\en
\& js_invalid_end Fix these fields and try again!
\& js_invalid_select - You must choose an option for the "%s" field\en
.Ve
Alternatively, you could specify this directly as a hashref:
.Sp
.Vb 8
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& messages => {
\& js_invalid_start => '%s error(s) were found in your form:\en',
\& js_invalid_end => 'Fix these fields and try again!',
\& js_invalid_select => '- Choose an option from the "%s" list\en',
\& }
\& );
.Ve
Although in practice this is rarely useful, unless you just want to
tweak one or two things.
.Sp
This system is easy, are there are many many messages that can be
customized. Here is a list of the fields that can be customized,
along with their default values.
.Sp
.Vb 2
\& js_invalid_start %s error(s) were encountered with your submission:
\& js_invalid_end Please correct these fields and try again.
.Ve
.Vb 7
\& js_invalid_input - You must enter a valid value for the "%s" field
\& js_invalid_select - You must choose an option for the "%s" field
\& js_invalid_checkbox - You must choose an option for the "%s" field
\& js_invalid_radio - You must choose an option for the "%s" field
\& js_invalid_password - You must enter a valid value for the "%s" field
\& js_invalid_textarea - You must fill in the "%s" field
\& js_invalid_file - You must specify a valid file for the "%s" field
.Ve
.Vb 1
\& form_required_text
Fields shown in bold are required.
.Ve
.Vb 3
\& form_invalid_text
%s error(s) were encountered with your submission.
\& Please correct the fields
\& highlighted below.
.Ve
.Vb 1
\& form_invalid_color red
.Ve
.Vb 1
\& form_confirm_text Success! Your submission has been received %s.
.Ve
.Vb 7
\& form_invalid_input You must enter a valid value
\& form_invalid_select You must choose an option from this list
\& form_invalid_checkbox You must choose an option from this group
\& form_invalid_radio You must choose an option from this group
\& form_invalid_password You must enter a valid value
\& form_invalid_textarea You must fill in this field
\& form_invalid_file You must specify a valid filename
.Ve
.Vb 3
\& form_select_default -select-
\& form_submit_default Submit
\& form_reset_default Reset
.Ve
The \f(CW\*(C`js_\*(C'\fR tags are used in JavaScript alerts, whereas the \f(CW\*(C`form_\*(C'\fR tags
are used in \s-1HTML\s0 and templates managed by FormBuilder.
.Sp
In some of the messages, you will notice a \f(CW\*(C`%s\*(C'\fR \f(CW\*(C`printf\*(C'\fR format. This
is because these messages will include certain details for you. For example,
the \f(CW\*(C`js_invalid_start\*(C'\fR tag will print the number of errors if you include
the \f(CW\*(C`%s\*(C'\fR format tag. Of course, you this is optional, so if you leave it
out then you won't get the number of errors.
.Sp
The best way to get an idea of how these work is to experiment a little.
It should become obvious really quickly.
.Ip "debug => 0 | 1 | 2" 4
.IX Item "debug => 0 | 1 | 2"
If set to 1, the module spits copious debugging info to \s-1STDERR\s0.
If set to 2, it spits out even more gunk. Defaults to 0.
.Sh "\fIrender()\fP"
.IX Subsection "render()"
This function renders the form into \s-1HTML\s0, and returns a string
containing the form. The most common use is simply:
.PP
.Vb 1
\& print $form->render;
.Ve
However, \f(CW\*(C`render()\*(C'\fR accepts \fBthe exact same options\fR as \f(CW\*(C`new()\*(C'\fR
Why? Because this allows you to set certain options at different
points in your code, which is often useful. For example, you could
change the formatting based on whether \f(CW\*(C`layout\*(C'\fR appeared in the
query string:
.PP
.Vb 2
\& my $form = CGI::FormBuilder->new(method => 'POST',
\& fields => [qw/name email/]);
.Ve
.Vb 2
\& # Get our layout from an extra CGI param
\& my $layout = $form->cgi_param('layout');
.Ve
.Vb 6
\& # If we're using a layout, then make sure to request a template
\& if ($layout) {
\& print $form->render(template => $layout);
\& } else {
\& print $form->render(header => 1);
\& }
.Ve
The following are all the options accepted by both \f(CW\*(C`new()\*(C'\fR and
\&\f(CW\*(C`render()\*(C'\fR:
.Ip "action => \f(CW$script\fR" 4
.IX Item "action => $script"
What script to point the form to. Defaults to itself, which is
the recommended setting.
.Ip "body => \e%hash" 4
.IX Item "body => %hash"
This takes a hashref of attributes that will be stuck in the
\&\f(CW\*(C`
\*(C'\fR tag verbatim (for example, bgcolor, alink, etc).
If you're thinking about using this, also check out the
\&\f(CW\*(C`template\*(C'\fR option above (and below).
.Ip "fieldtype => 'type'" 4
.IX Item "fieldtype => 'type'"
This can be used to set the default type for all fields. For example,
if you're writing a survey application, you may want all of your
fields to be of type \f(CW\*(C`textarea\*(C'\fR by default. Easy:
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(... fieldtype => 'textarea');
.Ve
.Ip "fieldattr => { opt => val, opt => val }" 4
.IX Item "fieldattr => { opt => val, opt => val }"
Even more flexible than \f(CW\*(C`fieldtype\*(C'\fR, this option allows you to
specify \fIany\fR type of \s-1HTML\s0 attribute and have it be the default
for all fields. For example:
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(... fieldattr => { class => 'myClass' });
.Ve
Would set the \f(CW\*(C`class\*(C'\fR \s-1HTML\s0 attribute on all fields by default,
so that when they are printed out they will have a \f(CW\*(C`class="myClass"\*(C'\fR
part of their \s-1HTML\s0 tag. Maybe you want a template?
.Ip "font => \f(CW$font\fR | \e%fonttags" 4
.IX Item "font => $font | %fonttags"
The font face to use for the form. This is output as a series of
\&\f(CW\*(C`\*(C'\fR tags for best browser compatibility, and will even
take care of the tedious table elements. I use this option all the
time. If you specify a hashref instead of just a font name, then
each key/value pair will be taken as part of the \f(CW\*(C`\*(C'\fR tag.
For example:
.Sp
.Vb 1
\& font => {face => 'verdana', size => '-1', color => 'gray'}
.Ve
Would generate the following tag:
.Sp
.Vb 1
\&
.Ve
And properly nest them in all of the table elements.
.Ip "header => 0 | 1" 4
.IX Item "header => 0 | 1"
If set to 1, a valid \f(CW\*(C`Content\-type\*(C'\fR header will be printed out,
along with a whole bunch of \s-1HTML\s0 \f(CW\*(C`\*(C'\fR code, a \f(CW\*(C`\*(C'\fR
tag, and so on. This defaults to 0, since usually people end up using
templates or embedding forms in other \s-1HTML\s0. Setting it to 1 is a great
way to throw together a quick and dirty form, though.
.Ip "javascript => 0 | 1" 4
.IX Item "javascript => 0 | 1"
If set to 1, JavaScript is generated in addition to \s-1HTML\s0, the
default setting.
.Ip "jshead => \s-1JSCODE\s0" 4
.IX Item "jshead => JSCODE"
If using JavaScript, you can also specify some JavaScript code
that will be included verbatim in the section of the
document. I'm not very fond of this one, what you probably
want is the next option.
.Ip "jsfunc => \s-1JSCODE\s0" 4
.IX Item "jsfunc => JSCODE"
Just like \f(CW\*(C`jshead\*(C'\fR, only this is stuff that will go into the
\&\f(CW\*(C`validate\*(C'\fR JavaScript function. As such, you can use it to
add extra JavaScript validate code verbatim. If something fails,
you should do two things:
.Sp
.Vb 2
\& - append to the JS variable "alertstr"
\& - increment the JS variable "invalid"
.Ve
For example:
.Sp
.Vb 6
\& my $jsfunc = <new(... jsfunc => $jsfunc);
.Ve
Then, this code will be automatically called when form validation
is invoked. I find this option can be incredibly useful. Most often,
I use it to bypass validation on certain submit modes. The submit
button that was clicked is \f(CW\*(C`form._submit.value\*(C'\fR:
.Sp
.Vb 9
\& my $jsfunc = < 0 | 1 | \e@array" 4
.IX Item "keepextras => 0 | 1 | @array"
If set to 1, then extra parameters not set in your fields declaration
will be kept as hidden fields in the form. However, you will need
to use \f(CW\*(C`cgi_param()\*(C'\fR, not \f(CW\*(C`field()\*(C'\fR, to get to the values. This is
useful if you want to keep some extra parameters like referer or
company available but not have them be valid form fields. See below
under \f(CW\*(C`/"param"\*(C'\fR for more details.
.Sp
You can also specify an arrayref, in which case only params found on
that list will be preserved. For example, saying:
.Sp
.Vb 1
\& ->new(keepextras => 1, ...);
.Ve
Will preserve all non-field parameters, whereas saying:
.Sp
.Vb 1
\& ->new(keepextras => [qw/mode company/], ...);
.Ve
Will only preserve the params \f(CW\*(C`mode\*(C'\fR and \f(CW\*(C`company\*(C'\fR.
.Ip "labels => \e%hash" 4
.IX Item "labels => %hash"
Like \f(CW\*(C`values\*(C'\fR, this is a list of key/value pairs where the keys
are the names of \f(CW\*(C`fields\*(C'\fR specified above. By default, \fBFormBuilder\fR
does some snazzy case and character conversion to create pretty labels
for you. However, if you want to explicitly name your fields, use this
option.
.Sp
For example:
.Sp
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => [qw/name email/],
\& labels => {
\& name => 'Your Full Name',
\& email => 'Primary Email Address'
\& }
\& );
.Ve
Usually you'll find that if you're contemplating this option what
you really want is a template.
.Ip "lalign => 'left' | 'right' | 'center'" 4
.IX Item "lalign => 'left' | 'right' | 'center'"
This is how to align the field labels in the table layout. I really
don't like this option being here, but it does turn out to be
pretty damn useful. You should probably be using a template.
.Ip "linebreaks => 0 | 1" 4
.IX Item "linebreaks => 0 | 1"
If set to 1, line breaks will be inserted after each input field.
By default this is figured out for you, so usually not needed.
.Ip "method => '\s-1POST\s0' | '\s-1GET\s0'" 4
.IX Item "method => 'POST' | 'GET'"
Either \f(CW\*(C`POST\*(C'\fR or \f(CW\*(C`GET\*(C'\fR, the type of \s-1CGI\s0 method to use. Defaults
to \f(CW\*(C`GET\*(C'\fR if nothing is specified.
.Ip "options => \e%hash" 4
.IX Item "options => %hash"
By using this argument, you can avoid having to specify the options
for different fields individually:
.Sp
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => [qw/part_number department in_stock/],
\& options => {
\& department => [qw/hardware software/],
\& in_stock => [qw/yes no/],
\& }
\& );
.Ve
This will then create the appropriate multi-option \s-1HTML\s0 inputs (in
this case, radio groups) automatically.
.Ip "required => \e@array | '\s-1ALL\s0' | '\s-1NONE\s0'" 4
.IX Item "required => @array | 'ALL' | 'NONE'"
This is a list of those values that are required to be filled in.
Those fields named must be included by the user. If the \f(CW\*(C`required\*(C'\fR
option is not specified, by default any fields named in \f(CW\*(C`validate\*(C'\fR
will be required.
.Sp
As of v1.97, the \f(CW\*(C`required\*(C'\fR option now takes two other settings,
the string \f(CW\*(C`ALL\*(C'\fR and the string \f(CW\*(C`NONE\*(C'\fR. If you specify \f(CW\*(C`ALL\*(C'\fR,
then all fields are required. If you specify \f(CW\*(C`NONE\*(C'\fR, then none
of them are \fIin spite of what may be set via the \*(L"validate\*(R" option\fR.
.Sp
This is useful if you have fields that you need to be validated if
filled in, but which are optional. For example:
.Sp
.Vb 5
\& my $form = CGI::FormBuilder->new(
\& fields => qw[/name email/],
\& validate => { email => 'EMAIL' },
\& required => 'NONE'
\& );
.Ve
This would make the \f(CW\*(C`email\*(C'\fR field optional, but if filled in then
it would have to match the \f(CW\*(C`EMAIL\*(C'\fR pattern.
.Sp
In addition, it is \fIvery\fR important to note that if the \f(CW\*(C`required\*(C'\fR
\&\fIand\fR \f(CW\*(C`validate\*(C'\fR options are specified, then they are taken as an
intersection. That is, only those fields specified as \f(CW\*(C`required\*(C'\fR
must be filled in, and the rest are optional. For example:
.Sp
.Vb 5
\& my $form = CGI::FormBuilder->new(
\& fields => qw[/name email/],
\& validate => { email => 'EMAIL' },
\& required => [qw/name/]
\& );
.Ve
This would make the \f(CW\*(C`name\*(C'\fR field mandatory, but the \f(CW\*(C`email\*(C'\fR field
optional. However, if \f(CW\*(C`email\*(C'\fR is filled in, then it must match the
builtin \f(CW\*(C`EMAIL\*(C'\fR pattern.
.Ip "reset => 0 | \f(CW$string\fR" 4
.IX Item "reset => 0 | $string"
If set to 0, then the \*(L"Reset\*(R" button is not printed. If set to
text, then that will be printed out as the reset button. Defaults
to printing out a button that says \*(L"Reset\*(R".
.Ip "selectnum => \f(CW$threshold\fR" 4
.IX Item "selectnum => $threshold"
These affect the \*(L"intelligence\*(R" of the module. If a given field
has any options, then it will be a radio group by default. However,
if more than \f(CW\*(C`selectnum\*(C'\fR options are present, then it will become
a select list. The default is 5 or more options. For example:
.Sp
.Vb 3
\& # This will be a radio group
\& my @opt = qw(Yes No);
\& $form->field(name => 'answer', options => \e@opt);
.Ve
.Vb 3
\& # However, this will be a select list
\& my @states = qw(AK CA FL NY TX);
\& $form->field(name => 'state', options => \e@states);
.Ve
.Vb 2
\& # This is the one special case - single items are checkboxes
\& $form->field(name => 'answer', options => ['Yes']);
.Ve
There is no threshold for checkboxes since these are basically
a type of multiple radio select group. As such, a radio group
becomes a checkbox group if there are multiple values (not
options, but actual values) for a given field, or if you
specify \f(CW\*(C`multiple => 1\*(C'\fR to the \f(CW\*(C`field()\*(C'\fR method. Got it?
.Ip "smartness => 0 | 1 | 2" 4
.IX Item "smartness => 0 | 1 | 2"
By default \s-1CGI:\s0:FormBuilder tries to be pretty smart for you, like
figuring out the types of fields based on their names and number
of options. If you don't want this behavior at all, set \f(CW\*(C`smartness\*(C'\fR
to \f(CW\*(C`0\*(C'\fR. If you want it to be \fBreally\fR smart, like figuring
out what type of validation routines to use for you, set it to
\&\f(CW\*(C`2\*(C'\fR. It defaults to \f(CW\*(C`1\*(C'\fR.
.Ip "sortopts => alpha | numeric | \s-1NAME\s0 | \s-1NUM\s0 | 1" 4
.IX Item "sortopts => alpha | numeric | NAME | NUM | 1"
If specified to \f(CW\*(C`render()\*(C'\fR or \f(CW\*(C`new()\*(C'\fR, this has the same effect
as the same-named option to \f(CW\*(C`field()\*(C'\fR, only it applies to all fields.
.Ip "static => 0 | 1" 4
.IX Item "static => 0 | 1"
If set to 1, then the form will be output with static hidden
fields. Defaults to 0.
.Ip "sticky => 0 | 1" 4
.IX Item "sticky => 0 | 1"
Determines whether or not form values should be sticky across
submissions. This does \fInot\fR affect the value you get back from
a call to \f(CW\*(C`field()\*(C'\fR. It also does not affect default values. It
only affects values the user may have entered via the \s-1CGI\s0.
.Sp
This defaults to 1, meaning values are sticky. However, you may
want to set it to 0 if you have a form which does something like
adding parts to a database. See the the EXAMPLES entry elsewhere in this document section for
a good example.
.Ip "submit => 0 | \f(CW$string\fR | \e@array" 4
.IX Item "submit => 0 | $string | @array"
If set to 0, then the \*(L"Submit\*(R" button is not printed. It defaults
to creating a button that says \*(L"Submit\*(R" verbatim. If given an
argument, then that argument becomes the text to show. For example:
.Sp
.Vb 1
\& print $form->render(submit => 'Do Lookup');
.Ve
Would make it so the submit button says \*(L"Do Lookup\*(R" on it.
.Sp
If you pass an arrayref of multiple values, you get a key benefit.
This will create multiple submit buttons, each with a different value.
In addition, though, when submitted only the one that was clicked
will be sent across \s-1CGI\s0 via some JavaScript tricks. So this:
.Sp
.Vb 1
\& print $form->render(submit => ['Add A Gift', 'No Thank You']);
.Ve
Would create two submit buttons. Clicking on either would submit the
form, but you would be able to see which one was submitted via the
\&\f(CW\*(C`submitted()\*(C'\fR function:
.Sp
.Vb 1
\& my $clicked = $form->submitted;
.Ve
So if the user clicked \*(L"Add A Gift\*(R" then that is what would end up
in the variable \f(CW\*(C`$clicked\*(C'\fR above. This allows nice conditionality:
.Sp
.Vb 5
\& if ($form->submitted eq 'Add A Gift') {
\& # show the gift selection screen
\& } elsif ($form->submitted eq 'No Thank You')
\& # just process the form
\& }
.Ve
See the the EXAMPLES entry elsewhere in this document section for more details.
.Ip "table => 0 | 1 | \e%tabletags" 4
.IX Item "table => 0 | 1 | %tabletags"
By default \fBFormBuilder\fR decides how to layout the form based on
the number of fields, values, etc. You can force it into a table
by specifying \f(CW\*(C`1\*(C'\fR, or force it out of one with \f(CW\*(C`0\*(C'\fR.
.Sp
If you specify a hashref instead, then these will be used to
create the \f(CW\*(C`
\*(C'\fR tag. For example, to create a table
with no cellpadding or cellspacing, use:
.Sp
.Vb 1
\& table => {cellpadding => 0, cellspacing => 0}
.Ve
.Ip "template => \f(CW$filename\fR | \e%hash" 4
.IX Item "template => $filename | %hash"
This points to a filename that contains an \f(CW\*(C`HTML::Template\*(C'\fR
compatible template to use to layout the \s-1HTML\s0. You can also specify
the \f(CW\*(C`template\*(C'\fR option as a reference to a hash, allowing you to
further customize the template processing options.
.Sp
For example, you could turn on caching in \f(CW\*(C`HTML::Template\*(C'\fR with
something like the following:
.Sp
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& filename => 'form.tmpl',
\& shared_cache => 1
\& }
\& );
.Ve
In addition, specifying a hashref allows you to use an alternate template
processing system like the \f(CW\*(C`Template Toolkit\*(C'\fR. A minimal configuration
would look like this:
.Sp
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'TT2', # use Template Toolkit
\& template => 'form.tmpl',
\& },
\& );
.Ve
The \f(CW\*(C`type\*(C'\fR option specifies the name of the processor. Use \f(CW\*(C`TT2\*(C'\fR to
invoke the Template Toolkit or \f(CW\*(C`HTML\*(C'\fR (the default) to invoke
\&\f(CW\*(C`HTML::Template\*(C'\fR as shown above. All other options besides \f(CW\*(C`type\*(C'\fR
are passed to the constructor for that templating system verbatim,
so you'll need to consult those docs to see what different options do.
.Sp
For lots more information on templates, see the the TEMPLATES entry elsewhere in this document section
below.
.Ip "text => \f(CW$text\fR" 4
.IX Item "text => $text"
This is text that is included below the title but above the
actual form. Useful if you want to say something simple like
\&\*(L"Contact \f(CW$adm\fR for more help\*(R", but if you want lots of text
check out the \f(CW\*(C`template\*(C'\fR option above.
.Ip "title => \f(CW$title\fR" 4
.IX Item "title => $title"
This takes a string to use as the title of the form.
.Ip "valign => 'top' | 'middle' | 'bottom'" 4
.IX Item "valign => 'top' | 'middle' | 'bottom'"
Another one I don't like, this alters how form fields are laid out in
the natively-generated table. Default is \*(L"middle\*(R".
.Ip "values => \e%hash | \e@array" 4
.IX Item "values => %hash | @array"
The \f(CW\*(C`values\*(C'\fR option takes a hashref of key/value pairs specifying
the default values for the fields. These values will be overridden
by the values entered by the user across the \s-1CGI\s0. The values are
used case-insensitively, making it easier to use \s-1DBI\s0 hashref records
(which are in upper or lower case depending on your database).
.Sp
This option is useful for selecting a record from a database or
hardwiring some sensible defaults, and then including them in the
form so that the user can change them if they wish. For example:
.Sp
.Vb 3
\& my $rec = $sth->fetchrow_hashref;
\& my $form = CGI::FormBuilder->new(fields => \e@fields,
\& values => $rec);
.Ve
You can also pass an arrayref, in which case each value is used
sequentially for each field as specified to the \f(CW\*(C`fields\*(C'\fR option.
While \f(CW\*(C`new()\*(C'\fR is used as an example, this can of course be
used in \f(CW\*(C`render()\*(C'\fR as well.
.PP
Note that any other options specified are passed to the \f(CW\*(C`
.Ve
As you see, you get a \f(CW\*(C`\*(C'\fR for each for field you define.
.PP
However, you may want even more control. That is, maybe you want
to specify every nitty-gritty detail of your input fields, and
just want this module to take care of the statefulness of the
values. This is no problem, since this module also provides
several other \f(CW\*(C`\*(C'\fR tags as well:
.PP
.Vb 4
\& - The value of a given field
\& - The human-readable label
\& - Any optional comment
\& - Error text if validation fails
.Ve
This means you could say something like this in your template:
.PP
.Vb 3
\& :
\&
\&
.Ve
And \fBFormBuilder\fR would take care of the value stickiness for you,
while you have control over the specifics of the \f(CW\*(C`\*(C'\fR tag.
A sample expansion may create \s-1HTML\s0 like the following:
.PP
.Vb 3
\& Email:
\&
\& You must enter a valid value
.Ve
Note, though, that this will only get the \fIfirst\fR value in the case
of a multi-value parameter (for example, a multi-select list). To
remedy this, if there are multiple values you will also get a
\&\f(CW\*(C`\*(C'\fR prefixed with \*(L"loop-\*(R". So, if you had:
.PP
.Vb 1
\& myapp.cgi?color=gray&color=red&color=blue
.Ve
This would give the \f(CW\*(C`color\*(C'\fR field three values. To create a select
list, you would do this in your template:
.PP
.Vb 5
\&
.Ve
With \f(CW\*(C`\*(C'\fR tags, each iteration gives you several
variables:
.PP
.Vb 6
\& Inside , this... Gives you this
\& --------------------------- -------------------------------
\& value of that option
\& label for that option
\& if selected, the word "checked"
\& if selected, the word "selected"
.Ve
Please note that \f(CW\*(C`\*(C'\fR gives you one of the \fIoptions\fR,
not the values. Why? Well, if you think about it you'll realize that
select lists and radio groups are fundamentally different from input
boxes in a number of ways. Whereas in input tags you can just have
an empty value, with lists you need to iterate through each option
and then decide if it's selected or not.
.PP
When you need precise control in a template this is all exposed to you;
normally \fBFormBuilder\fR does all this magic for you. If you don't need
exact control over your lists, simply use the \f(CW\*(C`\*(C'\fR
tag and this will all be done automatically, which I strongly recommend.
.PP
But, let's assume you need exact control over your lists. Here's an
example select list template:
.PP
.Vb 5
\&
.Ve
Then, your Perl code would fiddle the field as follows:
.PP
.Vb 2
\& $form->field(name => 'color', nameopts => 1,
\& options => [qw/red green blue yellow black white gray/]);
.Ve
Assuming query string as shown above, the template would then be expanded
to something like this:
.PP
.Vb 9
\&
.Ve
Notice that the \f(CW\*(C`\*(C'\fR tag is expanded to the word
\&\*(L"selected\*(R" when a given option is present as a value as well (i.e.,
via the \s-1CGI\s0 query). The \f(CW\*(C`\*(C'\fR tag expands to each option
in turn, and \f(CW\*(C`\*(C'\fR is expanded to the label for that
value. In this case, since \f(CW\*(C`nameopts\*(C'\fR was specified to \f(CW\*(C`field()\*(C'\fR, the
labels are automatically generated from the options.
.PP
Let's look at one last example. Here we want a radio group that allows
a person to remove themself from a mailing list. Here's our template:
.PP
.Vb 9
\& Do you want to be on our mailing list?
\&
\&
\&
\&
\&
\&
\&
\&
.Ve
Then, we would twiddle our \f(CW\*(C`mailopt\*(C'\fR field via \f(CW\*(C`field()\*(C'\fR:
.PP
.Vb 5
\& $form->field(name => 'mailopt', options => [qw/1 0/],
\& labels => {
\& 1 => 'Yes, please keep me on it!',
\& 0 => 'No, remove me immediately.'
\& });
.Ve
When the template is rendered, the result would be something like this:
.PP
.Vb 2
\& Do you want to be on our mailing list?
\&
.Ve
.Vb 4
\&
\&
\&
\&
Yes, please keep me on it!
.Ve
.Vb 4
\&
\&
\&
\&
No, remove me immediately
.Ve
.Vb 1
\&
.Ve
When the form was then sumbmitted, you would access the values just
like any other field:
.PP
.Vb 5
\& if ($form->field('mailopt')) {
\& # is 1, so add them
\& } else {
\& # is 0, remove them
\& }
.Ve
Finally, you can also loop through each of the fields using the top-level
\&\f(CW\*(C`fields\*(C'\fR loop in your template. This allows you to reuse the
same template even if your parameters change. The following template
code would loop through each field, creating a table row for each:
.PP
.Vb 8
\&
\&
\&
\&
\&
\&
\&
\&
.Ve
Each loop will have a \f(CW\*(C`label\*(C'\fR, \f(CW\*(C`field\*(C'\fR, \f(CW\*(C`value\*(C'\fR, etc, just like above.
.PP
For more information on templates, see the HTML::Template manpage.
.Sh "Template Toolkit"
.IX Subsection "Template Toolkit"
Thanks to a huge patch from Andy Wardley, \fBFormBuilder\fR also supports
\&\f(CW\*(C`Template Toolkit\*(C'\fR. This is enabled by specifying the following
options as a hashref to the \f(CW\*(C`template\*(C'\fR argument:
.PP
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'TT2', # use Template Toolkit
\& template => 'form.tmpl'
\& }
\& );
.Ve
By default, the Template Toolkit makes all the form and field
information accessible through simple variables.
.PP
.Vb 8
\& [% jshead %] - JavaScript to stick in
\& [% title %] - The of the HTML form
\& [% start %] - Opening
tag w/ options
\& [% submit %] - The submit button(s)
\& [% reset %] - The reset button
\& [% end %] - Closing
tag
\& [% fields %] - List of fields
\& [% field %] - Hash of fields (for lookup by name)
.Ve
You can specify the \f(CW\*(C`variable\*(C'\fR option to have all these variables
accessible under a certain namespace. For example:
.PP
.Vb 8
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'TT2',
\& template => 'form.tmpl',
\& variable => 'form'
\& },
\& );
.Ve
With \f(CW\*(C`variable\*(C'\fR set to \f(CW\*(C`form\*(C'\fR the variables are accessible as:
.PP
.Vb 3
\& [% form.jshead %]
\& [% form.start %]
\& etc.
.Ve
You can access individual fields via the \f(CW\*(C`field\*(C'\fR variable.
.PP
.Vb 5
\& For a field named... The field data is in...
\& -------------------- -----------------------
\& job [% form.field.job %]
\& size [% form.field.size %]
\& email [% form.field.email %]
.Ve
Each field contains various elements. For example:
.PP
.Vb 1
\& [% myfield = form.field.email %]
.Ve
.Vb 8
\& [% myfield.label %] # text label
\& [% myfield.field %] # field input tag
\& [% myfield.value %] # first value
\& [% myfield.values %] # list of all values
\& [% myfield.option %] # first value
\& [% myfield.options %] # list of all values
\& [% myfield.required %] # required flag
\& [% myfield.invalid %] # invalid flag
.Ve
The \f(CW\*(C`fields\*(C'\fR variable contains a list of all the fields in the form.
To iterate through all the fields in order, you could do something like
this:
.PP
.Vb 5
\& [% FOREACH field = form.fields %]
\&
\&
[% field.label %]
[% field.field %]
\&
\& [% END %]
.Ve
If you want to customise any of the Template Toolkit options, you can
set the \f(CW\*(C`engine\*(C'\fR option to contain a reference to an existing
\&\f(CW\*(C`Template\*(C'\fR object or hash reference of options which are passed to
the \f(CW\*(C`Template\*(C'\fR constructor. You can also set the \f(CW\*(C`data\*(C'\fR item to
define any additional variables you want accesible when the template
is processed.
.PP
.Vb 15
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'TT2',
\& template => 'form.tmpl',
\& variable => 'form'
\& engine => {
\& INCLUDE_PATH => '/usr/local/tt2/templates',
\& },
\& data => {
\& version => 1.23,
\& author => 'Fred Smith',
\& },
\& },
\& );
.Ve
For further details on using the Template Toolkit, see \f(CW\*(C`Template\*(C'\fR or
www.template-toolkit.org
.Sh "Text::Template"
.IX Subsection "Text::Template"
Also thanks to a user contribution, this time by Jonathan Buhacoff,
\&\f(CW\*(C`Text::Template\*(C'\fR is also supported. Usage is very similar to Template Toolkit:
.PP
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'Text', # use Text::Template
\& template => 'form.tmpl',
\& }
\& );
.Ve
The default options passed into \f(CW\*(C`Text::Template\-\*(C'\fR\fInew()\fR> with this
calling form are:
.PP
.Vb 3
\& TYPE => 'FILE'
\& SOURCE => 'form.tmpl'
\& DELIMITERS => ['<%','%>']
.Ve
As these params are passed for you, your template will look very similar to
ones used by Template Toolkit and \f(CW\*(C`HTML::Mason\*(C'\fR (the Text::Template default
delimiters are \f(CW\*(C`{\*(C'\fR and \f(CW\*(C`}\*(C'\fR, but using alternative delimiters speeds it up by
about 25%, and the \f(CW\*(C`<%\*(C'\fR and \f(CW\*(C`%>\*(C'\fR delimiters are good,
familiar-looking alternatives).
.PP
.Vb 8
\& <% $jshead %> - JavaScript to stick in
\& <% $title %> - The of the HTML form
\& <% $start %> - Opening
tag w/ options
\& <% $submit %> - The submit button(s)
\& <% $reset %> - The reset button
\& <% $end %> - Closing
tag
\& <% $fields %> - List of fields
\& <% $field %> - Hash of fields (for lookup by name)
.Ve
Note that you refer to variables with a preceding \f(CW\*(C`$\*(C'\fR, just like in Perl.
Like Template Toolkit, you can specify a variable to place fields under:
.PP
.Vb 8
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'Text',
\& template => 'form.tmpl',
\& variable => 'form'
\& },
\& );
.Ve
Unlike Template Toolkit, though, these will not be placed in OO-style, dot-separated
vars. Instead, a hash will be created which you then reference:
.PP
.Vb 3
\& <% $form{jshead} %>
\& <% $form{start} %>
\& etc.
.Ve
And field data is in a hash-of-hashrefs format:
.PP
.Vb 5
\& For a field named... The field data is in...
\& -------------------- -----------------------
\& job <% $form{field}{job} %]
\& size <% $form{field}{size} %]
\& email <% $form{field}{email} %]
.Ve
Since \f(CW\*(C`Text::Template\*(C'\fR looks so much like Perl, you can access individual
elements and create variables like so:
.PP
.Vb 11
\& <%
\& my $myfield = $form{field}{email};
\& $myfield->{label}; # text label
\& $myfield->{field}; # field input tag
\& $myfield->{value}; # first value
\& $myfield->{values}; # list of all values
\& $myfield->{option}; # first option
\& $myfield->{options}; # list of all options
\& $myfield->{required}; # required flag
\& $myfield->{invalid}; # invalid flag
\& %>
.Ve
.Vb 5
\& <%
\& for my $field (@{$form{fields}}) {
\& $OUT .= "
\en
" . $field->{label} . "
" . $field->{field} . "
\en
";
\& }
\& %>
.Ve
In addition, when using the engine option, as in Template Toolkit, you can
supply an existing Text::Template object or a hash of parameters to be passed
to \f(CW\*(C`new()\*(C'\fR. For example, you can ask for different delimiters yourself:
.PP
.Vb 15
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'Text',
\& template => 'form.tmpl',
\& variable => 'form',
\& engine => {
\& DELIMITERS => [ '[@--', '--@]' ],
\& },
\& data => {
\& version => 1.23,
\& author => 'Fred Smith',
\& },
\& },
\& );
.Ve
If you pass a hash of parameters, you can override the \f(CW\*(C`TYPE\*(C'\fR and \f(CW\*(C`SOURCE\*(C'\fR parameters,
as well as any other \f(CW\*(C`Text::Template\*(C'\fR options. For example, you can pass in a string
template with \f(CW\*(C`TYPE => STRING\*(C'\fR instead of loading it from a file. You must
specify \fBboth\fR \f(CW\*(C`TYPE\*(C'\fR and \f(CW\*(C`SOURCE\*(C'\fR if doing so. The good news is this is trivial:
.PP
.Vb 16
\& my $form = CGI::FormBuilder->new(
\& fields => \e@fields,
\& template => {
\& type => 'Text',
\& variable => 'form',
\& engine => {
\& TYPE => 'STRING',
\& SOURCE => $string,
\& DELIMITERS => [ '[@--', '--@]' ],
\& },
\& data => {
\& version => 1.23,
\& author => 'Fred Smith',
\& },
\& },
\& );
.Ve
If you get the crazy idea to let users of your application pick the template file
(strongly discouraged) and you're getting errors, look at the \f(CW\*(C`Text::Template\*(C'\fR
documentation for the \f(CW\*(C`UNTAINT\*(C'\fR feature.
.PP
Also, note that \f(CW\*(C`Text::Template\*(C'\fR's \f(CW\*(C`PREPEND => 'use strict;'\*(C'\fR option is not
recommended due to the dynamic nature for \f(CW\*(C`FormBuilder\*(C'\fR. If you use it, then you'll
have to declare each variable that \f(CW\*(C`FormBuilder\*(C'\fR puts into your template with
\&\f(CW\*(C`use vars qw($jshead' ... etc);\*(C'\fR
.PP
If you're really stuck on this, though, a workaround is to say:
.PP
.Vb 1
\& PREPEND => 'use strict; use vars qw(%form);'
.Ve
and then set the option \f(CW\*(C`variable => 'form'\*(C'\fR. That way you can have strict Perl
without too much hassle, except that your code might be exhausting to look at :\-).
Things like \f(CW\*(C`$form{field}{your_field_name}{field}\*(C'\fR end up being all over the place,
instead of the nicer short forms.
.PP
Finally, when you use the \f(CW\*(C`data\*(C'\fR template option, the keys you specify will be available
to the template as regular variables. In the above example, these would be
\&\f(CW\*(C`<% $version %>\*(C'\fR and \f(CW\*(C`<% $author %>\*(C'\fR. And complex datatypes are easy:
.PP
.Vb 4
\& data => {
\& anArray => [ 1, 2, 3 ],
\& aHash => { orange => 'tangy', chocolate => 'sweet' },
\& }
.Ve
This becomes the following in your template:
.PP
.Vb 4
\& <%
\& @anArray; # you can use $myArray[1] etc.
\& %aHash; # you can use $myHash{chocolate} etc.
\& %>
.Ve
For more information, please consult the \f(CW\*(C`Text::Template\*(C'\fR documentation.
.SH "EXAMPLES"
.IX Header "EXAMPLES"
I find this module incredibly useful, so here are even more examples,
pasted from sample code that I've written:
.Sh "Ex1: order.cgi"
.IX Subsection "Ex1: order.cgi"
This example provides an order form complete with validation of the
important fields.
.PP
.Vb 1
\& #!/usr/bin/perl -w
.Ve
.Vb 2
\& use strict;
\& use CGI::FormBuilder;
.Ve
.Vb 3
\& my @states = qw(AL AK AZ AR CA CO CT DE DC FL GE HI ID IL IN IA KS
\& KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC
\& ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY);
.Ve
.Vb 7
\& my $form = CGI::FormBuilder->new(
\& header => 1, method => 'POST', title => 'Order Info',
\& fields => [qw/first_name last_name email address
\& state zipcode credit_card/],
\& validate => {email => 'EMAIL', zipcode => 'ZIPCODE',
\& credit_card => 'CARD'}
\& );
.Ve
.Vb 1
\& $form->field(name => 'state', options => \e@states, sort => 'alpha');
.Ve
.Vb 2
\& # This adds on the 'details' field to our form dynamically
\& $form->field(name => 'details', cols => '50', rows => '10');
.Ve
.Vb 7
\& # try to validate it first
\& if ($form->submitted && $form->validate) {
\& # ... more code goes here to do stuff ...
\& print $form->confirm;
\& } else {
\& print $form->render;
\& }
.Ve
This will create a form called \*(L"Order Info\*(R" that will provide a pulldown
menu for the \*(L"state\*(R", a textarea for the \*(L"details\*(R", and normal text
boxes for the rest. It will then validate the fields specified to the
\&\f(CW\*(C`validate\*(C'\fR option appropriately.
.Sh "Ex2: order_form.cgi"
.IX Subsection "Ex2: order_form.cgi"
This is very similar to the above, only it uses the \f(CW\*(C`smartness\*(C'\fR option
to fill in the \*(L"state\*(R" options automatically, as well as guess at the
validation types we want. I recommend you use the \f(CW\*(C`debug\*(C'\fR option to
see what's going on until you're sure it's doing what you want.
.PP
.Vb 1
\& #!/usr/bin/perl -w
.Ve
.Vb 2
\& use strict;
\& use CGI::FormBuilder;
.Ve
.Vb 6
\& my $form = CGI::FormBuilder->new(
\& header => 1, method => 'POST',
\& smartness => 2, debug => 2,
\& fields => [qw/first_name last_name email address
\& state zipcode credit_card/],
\& );
.Ve
.Vb 2
\& # This adds on the 'details' field to our form dynamically
\& $form->field(name => 'details', cols => '50', rows => '10');
.Ve
.Vb 7
\& # try to validate it first
\& if ($form->submitted && $form->validate) {
\& # ... more code goes here to do stuff ...
\& print $form->confirm;
\& } else {
\& print $form->render;
\& }
.Ve
Since we didn't specify the \f(CW\*(C`title\*(C'\fR option, it will be automatically
determined from the name of the executable. In this case it will be
\&\*(L"Order Form\*(R".
.Sh "Ex3: ticket_search.cgi"
.IX Subsection "Ex3: ticket_search.cgi"
This is a simple search script that uses a template to layout
the search parameters very precisely. Note that we set our
options for our different fields and types.
.PP
.Vb 1
\& #!/usr/bin/perl -w
.Ve
.Vb 2
\& use strict;
\& use CGI::FormBuilder;
.Ve
.Vb 4
\& my $form = CGI::FormBuilder->new(
\& header => 1, template => 'ticket_search.tmpl',
\& fields => [qw/type string status category/]
\& );
.Ve
.Vb 3
\& # Need to setup some specific field options
\& $form->field(name => 'type',
\& options => [qw/ticket requestor hostname sysadmin/]);
.Ve
.Vb 2
\& $form->field(name => 'status', type => 'radio', value => 'incomplete',
\& options => [qw/incomplete recently_completed all/]);
.Ve
.Vb 2
\& $form->field(name => 'category', type => 'checkbox',
\& options => [qw/server network desktop printer/]);
.Ve
.Vb 2
\& # Render the form and print it out so our submit button says "Search"
\& print $form->render(submit => ' Search ');
.Ve
Then, in our \f(CW\*(C`ticket_search.tmpl\*(C'\fR \s-1HTML\s0 file, we would have something like this:
.PP
.Vb 22
\&
\&
\& Search Engine
\&
\&
\&
\&
\&
\& Please enter a term to search the ticket database. Make sure
\& to "quote phrases".
\&
\&
\& Search by for
\&
\&
\& Status:
\&
\& Category:
\&
\&
\&
\&
.Ve
That's all you need for a sticky search form with the above \s-1HTML\s0 layout.
Notice that you can change the \s-1HTML\s0 layout as much as you want without
having to touch your \s-1CGI\s0 code.
.Sh "Ex4: user_info.cgi"
.IX Subsection "Ex4: user_info.cgi"
This script grabs the user's information out of a database and lets
them update it dynamically. The \s-1DBI\s0 information is provided as an
example, your mileage may vary:
.PP
.Vb 1
\& #!/usr/bin/perl -w
.Ve
.Vb 4
\& use strict;
\& use CGI::FormBuilder;
\& use DBI;
\& use DBD::Oracle
.Ve
.Vb 1
\& my $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass');
.Ve
.Vb 6
\& # We create a new form. Note we've specified very little,
\& # since we're getting all our values from our database.
\& my $form = CGI::FormBuilder->new(
\& fields => [qw/username password confirm_password
\& first_name last_name email/]
\& );
.Ve
.Vb 5
\& # Now get the value of the username from our app
\& my $user = $form->cgi_param('user');
\& my $sth = $dbh->prepare("select * from user_info where user = '$user'");
\& $sth->execute;
\& my $default_hashref = $sth->fetchrow_hashref;
.Ve
.Vb 4
\& # Render our form with the defaults we got in our hashref
\& print $form->render(values => $default_hashref,
\& title => "User information for '$user'",
\& header => 1);
.Ve
.Sh "Ex5: add_part.cgi"
.IX Subsection "Ex5: add_part.cgi"
This presents a screen for users to add parts to an inventory database.
Notice how it makes use of the \f(CW\*(C`sticky\*(C'\fR option. If there's an error,
then the form is presented with sticky values so that the user can
correct them and resubmit. If the submission is ok, though, then the
form is presented without sticky values so that the user can enter
the next part.
.PP
.Vb 1
\& #!/usr/bin/perl -w
.Ve
.Vb 2
\& use strict;
\& use CGI::FormBuilder;
.Ve
.Vb 13
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/sn pn model qty comments/],
\& labels => { sn => 'Serial Number',
\& pn => 'Part Number' },
\& sticky => 0,
\& header => 1,
\& required => [qw/sn pn model qty/],
\& validate => { sn => '/^\ed{3}-\ed{4}-\ed{4}$/',
\& pn => '/^\ed{3}-\ed{4}$/',
\& qty => 'INT' },
\& font => 'arial,helvetica'
\& );
.Ve
.Vb 3
\& # shrink the qty field for prettiness, lengthen model
\& $form->field(name => 'qty', size => 4);
\& $form->field(name => 'model', size => 60);
.Ve
.Vb 9
\& if ($form->submitted) {
\& if ($form->validate) {
\& # Add part to database
\& } else {
\& # Invalid; show form and allow corrections
\& print $form->render(sticky => 1);
\& exit;
\& }
\& }
.Ve
.Vb 2
\& # Print form for next part addition.
\& print $form->render;
.Ve
With the exception of the database code, that's the whole application.
.SH "FREQUENTLY ASKED QUESTIONS (FAQ)"
.IX Header "FREQUENTLY ASKED QUESTIONS (FAQ)"
There are a couple questions and subtle traps that seem to poke people
on a regular basis. Here are some hints.
.Sh "I'm confused. Why doesn't \fIfield()\fP work like \s-1CGI\s0's \fIparam()\fP?"
.IX Subsection "I'm confused. Why doesn't field() work like CGI's param()?"
If you're used to \f(CW\*(C`CGI.pm\*(C'\fR, you have to do a little bit of a brain
shift when working with this module.
.Sp
First, this module is designed to address fields as \fIabstract
entities\fR. That is, you don't create a \*(L"checkbox\*(R" or \*(L"radio group\*(R"
per se. Instead, you create a field named for the data you want
to collect. \fBFormBuilder\fR takes care of figuring out what the
most optimal \s-1HTML\s0 representation is for you.
.Sp
So, if you want a single-option checkbox, simply say something
like this:
.Sp
.Vb 1
\& $form->field(name => 'join_mailing_list', options => ['Yes']);
.Ve
If you want it to be checked by default, you add the \f(CW\*(C`value\*(C'\fR arg:
.Sp
.Vb 2
\& $form->field(name => 'join_mailing_list', options => ['Yes'],
\& value => 'Yes');
.Ve
You see, you're creating a field that has one possible option: \*(L"Yes\*(R".
Then, you're saying its current value is, in fact, \*(L"Yes\*(R". This will
result in \fBFormBuilder\fR creating a single-option field (which is
a checkbox by default) and selecting the requested value (meaning
that the box will be checked).
.Sp
If you want multiple values, then all you have to do is specify
multiple options:
.Sp
.Vb 2
\& $form->field(name => 'join_mailing_list', options => [qw/Yes No/],
\& value => 'Yes');
.Ve
Now you'll get a radio group, and \*(L"Yes\*(R" will be selected for you!
By viewing fields as data entities (instead of \s-1HTML\s0 tags) you
get much more flexibility and less code maintenance. If you want
to be able to accept multiple values, simply add the \f(CW\*(C`multiple\*(C'\fR arg:
.Sp
.Vb 2
\& $form->field(name => 'favorite_colors', multiple => 1,
\& options => [qw/red green blue]);
.Ve
Depending on the number of \f(CW\*(C`options\*(C'\fR you have, you'll get either
a set of checkboxes or a multiple select list (unless you manually
override this with the \f(CW\*(C`type\*(C'\fR arg). Regardless, though, to get the
data back all you have to say is:
.Sp
.Vb 1
\& my @colors = $form->field('favorite_colors');
.Ve
And the rest is taken care of for you.
.Sh "How do I make a multi-screen/multi-mode form?"
.IX Subsection "How do I make a multi-screen/multi-mode form?"
This is easily doable, but you have to remember a couple things. Most
importantly, that \fBFormBuilder\fR only knows about those fields you've
told it about. So, let's assume that you're going to use a special
parameter called \f(CW\*(C`mode\*(C'\fR to control the mode of your application so
that you can call it like this:
.Sp
.Vb 3
\& myapp.cgi?mode=list&...
\& myapp.cgi?mode=edit&...
\& myapp.cgi?mode=remove&...
.Ve
And so on. You need to do two things. First, you need the \f(CW\*(C`keepextras\*(C'\fR
option:
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(..., keepextras => 1);
.Ve
This will maintain the \f(CW\*(C`mode\*(C'\fR field as a hidden field across requests
automatically. Second, you need to realize that since the \f(CW\*(C`mode\*(C'\fR is
not a defined field, you have to get it via the \f(CW\*(C`cgi_param()\*(C'\fR method:
.Sp
.Vb 1
\& my $mode = $form->cgi_param('mode');
.Ve
This will allow you to build a large multiscreen application easily,
even integrating it with modules like \f(CW\*(C`CGI::Application\*(C'\fR if you want.
.Sp
You can also do this by simply defining \f(CW\*(C`mode\*(C'\fR as a field in your
\&\f(CW\*(C`fields\*(C'\fR declaration. The reason this is discouraged is because
when iterating over your fields you'll get \f(CW\*(C`mode\*(C'\fR, which you likely
don't want (since it's not \*(L"real\*(R" data).
.Sh "Why won't \s-1CGI:\s0:FormBuilder work with \s-1POST\s0 requests?"
.IX Subsection "Why won't CGI::FormBuilder work with POST requests?"
It will, but chances are you're probably doing something like this:
.Sp
.Vb 2
\& use CGI qw/:standard/;
\& use CGI::FormBuilder;
.Ve
.Vb 2
\& # Our "mode" parameter determines what we do
\& my $mode = param('mode');
.Ve
.Vb 12
\& # Change our form based on our mode
\& if ($mode eq 'view') {
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/.../],
\& );
\& } elsif ($mode eq 'edit') {
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/.../],
\& );
\& }
.Ve
The problem is this: Once you read a \f(CW\*(C`POST\*(C'\fR request, it's gone
forever. In the above code, what you're doing is having \f(CW\*(C`CGI.pm\*(C'\fR
read the \f(CW\*(C`POST\*(C'\fR request (on the first call of \f(CW\*(C`param()\*(C'\fR).
.Sp
Luckily, there is an easy solution. First, you need to modify
your code to use the \s-1OO\s0 form of \f(CW\*(C`CGI.pm\*(C'\fR. Then, simply specify
the \f(CW\*(C`CGI\*(C'\fR object you create to the \f(CW\*(C`params\*(C'\fR option of \fBFormBuilder\fR:
.Sp
.Vb 2
\& use CGI;
\& use CGI::FormBuilder;
.Ve
.Vb 1
\& my $cgi = CGI->new;
.Ve
.Vb 2
\& # Our "mode" parameter determines what we do
\& my $mode = $cgi->param('mode');
.Ve
.Vb 15
\& # Change our form based on our mode
\& # Note: since it is POST, must specify the 'params' option
\& if ($mode eq 'view') {
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/.../],
\& params => $cgi # get CGI params
\& );
\& } elsif ($mode eq 'edit') {
\& my $form = CGI::FormBuilder->new(
\& method => 'POST',
\& fields => [qw/.../],
\& params => $cgi # get CGI params
\& );
\& }
.Ve
Or, since \fBFormBuilder\fR gives you a \f(CW\*(C`cgi_param()\*(C'\fR function, you
could modify your code so you use \fBFormBuilder\fR exclusively.
.Sh "How do I make it so that the values aren't shown in the form?"
.IX Subsection "How do I make it so that the values aren't shown in the form?"
Easy.
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(sticky => 0, ...);
.Ve
By turning off the \f(CW\*(C`sticky\*(C'\fR option, you will still be able to access
the values, but they won't show up in the form.
.Sh "How do I manually override the value of a field?"
.IX Subsection "How do I manually override the value of a field?"
You must specify the \f(CW\*(C`force\*(C'\fR option:
.Sp
.Vb 1
\& $form->field(name => 'name_of_field', value => $value, force => 1);
.Ve
If you don't specify \f(CW\*(C`force\*(C'\fR, then any \s-1CGI\s0 value will always win.
.Sh "How can I change option \s-1XXX\s0 based on a conditional?"
.IX Subsection "How can I change option XXX based on a conditional?"
Remember that \f(CW\*(C`render()\*(C'\fR can take any option that \f(CW\*(C`new()\*(C'\fR can. This
means that you can set some features on your form sooner and others
later:
.Sp
.Vb 1
\& my $form = CGI::FormBuilder->new(method => 'POST');
.Ve
.Vb 1
\& my $mode = $form->cgi_param('mode');
.Ve
.Vb 10
\& if ($mode eq 'add') {
\& print $form->render(fields => [qw/name email phone/],
\& title => 'Add a new entry');
\& } elsif ($mode eq 'edit') {
\& # do something to select existing values
\& my %values = select_values();
\& print $form->render(fields => [qw/name email phone/],
\& title => 'Edit existing entry',
\& values => \e%values);
\& }
.Ve
In fact, since any of the options can be used in either \f(CW\*(C`new()\*(C'\fR or
\&\f(CW\*(C`render()\*(C'\fR, you could have specified \f(CW\*(C`fields\*(C'\fR to \f(CW\*(C`new()\*(C'\fR above
since they are the same for both conditions.
.if n .Sh "I can't get ""validate"" to accept my regular expressions!"
.el .Sh "I can't get ``validate'' to accept my regular expressions!"
.IX Subsection "I can't get "validate to accept my regular expressions!"
You're probably not specifying them within single quotes. See the
section on \f(CW\*(C`validate\*(C'\fR above.
.Sh "Can FormBuilder handle file uploads?"
.IX Subsection "Can FormBuilder handle file uploads?"
It sure can, and it's really easy too. Just change the \f(CW\*(C`enctype\*(C'\fR
as an option to \f(CW\*(C`new()\*(C'\fR:
.Sp
.Vb 6
\& use CGI::FormBuilder;
\& my $form = CGI::FormBuilder->new(
\& enctype => 'multipart/form-data',
\& method => 'POST',
\& fields => [qw/filename/]
\& );
.Ve
.Vb 1
\& $form->field(name => 'filename', type => 'file');
.Ve
And then get to your file the same way as \f(CW\*(C`CGI.pm\*(C'\fR:
.Sp
.Vb 2
\& if ($form->submitted) {
\& my $file = $form->field('filename');
.Ve
.Vb 6
\& # save contents in file, etc ...
\& open F, ">$dir/$file" or die $!;
\& while (<$file>) {
\& print F;
\& }
\& close F;
.Ve
.Vb 4
\& print $form->confirm(header => 1);
\& } else {
\& print $form->render(header => 1);
\& }
.Ve
In fact, that's a whole file upload program right there.
.SH "BUGS AND FEATURES"
.IX Header "BUGS AND FEATURES"
This has been used pretty thoroughly in a production environment
for a while now, so it's definitely stable, but I would be shocked
if it's bug-free. Bug reports and \fBespecially patches\fR to fix such
bugs are welcomed.
.PP
I'm always open to entertaining \*(L"new feature\*(R" requests, but before
sending me one, first try to work within this module's interface.
You can very likely do exactly what you want by using a template.
.SH "NOTES"
.IX Header "NOTES"
Parameters beginning with a leading underscore are reserved for
future use by this module. Use at your own peril.
.PP
This module does a \fBlot\fR of guesswork for you. This means that
sometimes (although hopefully rarely), you may be scratching your
head wondering \*(L"Why did it do that?\*(R". Just use the \f(CW\*(C`field\*(C'\fR
method to set things up the way you want and move on.
.PP
Due to too many incompatibilities with \s-1CGI\s0.pm, unfortunately
\&\f(CW\*(C`CGI::Minimal\*(C'\fR is no longer used. Sorry.
.PP
The output of the \s-1HTML\s0 generated natively may change slightly from
release to release. If you need precise control, use a template.
.PP
Every attempt has been made to make this module taint-safe (\-T).
However, due to the way tainting works, you may run into the
message \*(L"Insecure dependency\*(R" or \*(L"Insecure \f(CW$ENV\fR{\s-1PATH\s0}\*(R". If so,
make sure you are setting you \f(CW\*(C`$ENV{PATH}\*(C'\fR at the top of your
script. This is actually a good habit regardless.
.SH "SUPPORT"
.IX Header "SUPPORT"
For support, please start by visiting the FormBuilder website at:
.PP
.Vb 1
\& www.formbuilder.org
.Ve
This site has numerous tutorials and other documentation to help you
use FormBuilder to its full potential. If you can't find the answer
there, then join the mailing list by emailing:
.PP
.Vb 1
\& fbusers-subscribe@formbuilder.org
.Ve
To submit patches, please first join the mailing list and post your
question or issue. That way we can have a discussion about the best
way to address it.
.SH "ACKNOWLEDGEMENTS"
.IX Header "ACKNOWLEDGEMENTS"
This module has really taken off, thanks to very useful input, bug
reports, and encouraging feedback from a number of people, including:
.PP
.Vb 25
\& Jakob Curdes
\& Mark Belanger
\& Peter Billam
\& Brad Bowman
\& Jonathan Buhacoff
\& Godfrey Carnegie
\& Bob Egert
\& Adam Foxson
\& Florian Helmberger
\& Mark Houliston
\& Robert James Kaes
\& Dimitry Kharitonov
\& Randy Kobes
\& William Large
\& Kevin Lubic
\& Robert Mathews
\& Mehryar
\& Koos Pol
\& Shawn Poulson
\& Dan Collis Puro
\& Stephan Springl
\& Ryan Tate
\& John Theus
\& Remi Turboult
\& Andy Wardley
.Ve
Thanks!
.SH "SEE ALSO"
.IX Header "SEE ALSO"
the HTML::Template manpage, the Text::Template manpage, Template Toolkit, the CGI::Minimal manpage,
the CGI manpage, the CGI::Application manpage
.SH "VERSION"
.IX Header "VERSION"
$Id: FormBuilder.pod,v 2.12 2003/07/25 21:17:30 nwiger Exp nwiger $
.SH "AUTHOR"
.IX Header "AUTHOR"
Copyright (c) 2001\-2003 Nathan Wiger, Sun Microsystems .
All Rights Reserved.
.PP
This module is free software; you may copy this under the terms of
the \s-1GNU\s0 General Public License, or the Artistic License, copies of
which should have accompanied your Perl kit.