NAME CGI::FormBuilder - Easily generate and process stateful forms SYNOPSIS use CGI::FormBuilder; # Ex 1 # Simplest version: print out a form with 3 fields # This is all you need for a simple form-based app! my $form = CGI::FormBuilder->new(fields => [qw/name job money/], title => 'Your Occupation'); print $form->render(header => 1); # Ex 1a # If we have default values, for example from a DBI query, # we can pass these in as well: my $dbi_results_hashref = $sth->fetchrow_hashref; print $form->render(values => $dbi_values_hashref); # Ex 1b # Now we're going to modify the attributes of individual # fields before printing them out. Normally, FormBuilder # will figure this out for you automagically, but you may # want to customize it: $form->field(name => 'job', type => 'checkbox'); $form->field(name => 'state', type => 'select', options => \@states); print $form->render(header => 1); # Ex 2 # Now we decide that we want to validate certain fields. # To do this we pass the 'validate' option. my $valid_form = CGI::FormBuilder->new( fields => [qw/name email/], validate => {name => 'WORD', email => 'EMAIL'} ); print $valid_form->render(header => 1); # Ex 3 # Finally, we've decided that the builtin forms, while # nice, are not as pretty as we'd like them to be. So, # we construct a template via HTML::Template and specify # it as what to use during printing: my $nice_form = CGI::FormBuilder->new( fields => [qw/username password/], template => 'userinfo.html' ); # Ex 4 # Or, if we prefer to use the Template Toolkit (TT2), # we can do it like this: my $nice_form = CGI::FormBuilder->new( fields => [qw/username password/], template => { type => 'TT2', template => 'userinfo.html', }, ); print $nice_form->render(header => 1); # Ex 5 # Of course, we can even build a complete application # using this module, since all fields are sticky and # stateful across multiple submissions. And, though # we're using anonymous arrayrefs []'s and hashrefs {}'s # above there's no reason we can't use named ones: my $loopback_form = CGI::FormBuilder->new( title => $title, fields => \@fields, values => \%values, validate => \%validate ); if ($loopback_form->submitted && $loopback_form->validate) { # We have a valid form that has been submitted # Here we would do stuff to use the different # values, and then finally print out a confirmation print $loopback_form->confirm; } else { print $loopback_form->render; } DESCRIPTION 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 HTML code: # The manual way print qq(); # The module way print input(-name => 'email', -type => 'text', -size => '20'); The problem is, that doesn't really gain you anything. You still have just as much code. Modules like the venerable "CGI.pm" are great for processing parameters, but they don't save you much time when trying to generate and process forms. The goal of "CGI::FormBuilder" is to provide an easy way for you to generate and process CGI form-based applications. This module is designed to be smart in that it figures a lot of stuff out for you. As a result, FormBuilder gives you about a 4:1 ratio of the code it generates versus what you have to write. 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 ("order_form.cgi" becomes "Order Form"). Plus, FormBuilder 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 ("stickiness") across submissions, with hooks provided for you to plugin your own sessionid module such as "Apache::Session". 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 "HTML::Template" or Template Toolkit ("Template") compatible template which will be automatically filled in, statefully. Walkthrough Let's walk through a whole example to see how this works. The basic usage is straightforward, and has these steps: 1. Create a new "CGI::FormBuilder" object with the proper options 2. Modify any fields that may need fiddling with 3. Validate the form, if applicable, and print it out Again, this module is designed to handle defaults intelligently for you. In fact, a whole form-based application can be output with nothing more than: use CGI::FormBuilder; my @fields = qw(name email password confirm_password zipcode); my $form = CGI::FormBuilder->new(fields => \@fields) print $form->render; Not only does this generate about 4 times as much XHTML-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 "validate" option to "new()": my $form = CGI::FormBuilder->new(fields => \@fields, validate => {email => 'EMAIL'}); You now get a whole set of JavaScript validation code, as well as Perl hooks for validation. In total you get about 6 times the amount of code generated versus written. Plus, statefulness and validation are handled for you, automatically. 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 "HTML::Template" compatible template and tell our module to use that. The "HTML::Template" module uses special XHTML 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:
Your full name: Your email address: Choose a password: Please confirm it: Your home zipcode:
[% FOREACH field = form.fields %]
[% form.end %]
So, as you can see, there is plugin capability for FormBuilder to
basically "run" the two major templating engines, HTML::Template and
Template Toolkit.
Now, back to FormBuilder. 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:
$form->validate;
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.
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 "confirm()"
method to print out a generic results page:
if ($form->validate) {
# form was good, let's update database ...
print $form->confirm;
} else {
print $form->render;
}
The "validate()" method will use whatever criteria were passed into
"new()" via the "validate" parameter to check the form submission to
make sure it's correct.
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:
if ($form->submitted && $form->validate) {
# form was good, let's update database ...
print $form->confirm;
} else {
print $form->render;
}
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 "mailconfirm()":
$form->mailconfirm(to => $email, from => $adm);
Now, any values you specify are automatically overridden by whatever the
user enters into the form and submits. These can then be gotten to by
the "field()" method:
my $email = $form->field(name => 'email');
Of course, like "CGI.pm's param()" you can just specify the name:
my $email = $form->field('email');
FormBuilder is good at giving you the data that you should be getting.
That is, let's say that you initially setup your $form object to use a
hash of existing values from a database select or something. Then, you
"render()" the form, the user fills it out, and submits it. When you
call "field()", you'll get whatever the correct value is, either the
default or what the user entered across the CGI.
So, our complete code thus far looks like this:
use CGI::FormBuilder;
my @fields = qw(name email password confirm_password zipcode);
my $form = CGI::FormBuilder->new(
fields => \@fields,
validate => {email => 'EMAIL'},
template => 'userinfo.html',
header => 1
);
if ($form->submitted && $form->validate) {
# form was good, let's update database ...
# and send them email about their submission
$form->mailconfirm(to => $form->field('email'), from => $adm);
# and show a confirmation message
print $form->confirm;
} else {
# print the form for them to fill out
print $form->render;
}
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.
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 is you want to pass arrays intact
into functions in Perl 5.
A reference is taken by preceding the variable with a backslash (\). In
our examples above, you saw something similar to this:
my @fields = ('name', 'email'); # same as = qw(name email)
my $form = CGI::FormBuilder->new(fields => \@fields ... );
Here, "\@fields" is a reference. Specifically, it's an array reference,
or "arrayref" for short.
Similarly, we can do the same thing with hashes:
my %validate = (
name => 'NAME';
email => 'EMAIL',
);
my $form = CGI::FormBuilder->new( ... validate => \%validate);
Here, "\%validate" is a hash reference, or "hashref".
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 CPAN modules.
Finally, there are two more types of references: anonymous arrayrefs and
anonymous hashrefs. These are created with "[]" and "{}", respectively.
So, for our purposes there is no real difference between this code:
my @fields = qw(name email);
my %validate = (name => 'NAME', email => 'EMAIL');
my $form = CGI::FormBuilder->new(
fields => \@fields,
validate => \%validate
);
And this code:
my $form = CGI::FormBuilder->new(
fields => [ qw(name email) ],
validate => { name => 'NAME', email => 'EMAIL' }
);
Except that the latter doesn't require that we first create @fields and
%validate variables.
Now back to our regularly-scheduled program...
FUNCTIONS
Of course, in the spirit of flexibility this module takes a bizillion
different options. None of these are mandatory - you can call the
"new()" constructor without any fields, but your form will be really
really short. :-)
new(opt => $val, opt => $val)
This is the constructor, and must be called very first. It returns a
$form object, which you can then modify and print out to create the
form. Options will be described shortly.
render(opt => $val, opt => $val)
This function renders the form into HTML, and returns a string
containing the form. The most common use is simply:
print $form->render;
However, "render()" accepts the exact same options as "new()" Why?
Because this allows you to set certain options at different points in
your code, which is often useful. For example, you can change the fields
depending on some conditional:
my $form = CGI::FormBuilder->new(method => 'POST');
if ($form->submitted) {
# second form
print $form->render(fields => [qw/email address/]);
} else {
# first form
print $form->render(fields => [qw/name phone/]);
}
The following are all the options accepted by both "new()" and
"render()":
action => $script
What script to point the form to. Defaults to itself, which is the
recommended setting.
body => \%hash
This takes a hashref of attributes that will be stuck in the
"" tag verbatim (for example, bgcolor, alink, etc). If you're
thinking about using this, check out the "template" option above
(and below).
debug => 0 | 1 | 2
If set to 1, the module spits copious debugging info to STDERR. If
set to 2, it spits out even more gunk. Defaults to 0.
fields => \@array
The "fields" 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.
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 "textarea". Easy:
my $form = CGI::FormBuilder->new(fields => ..., fieldtype => 'textarea');
fieldattr => { opt => val, opt => val }
Even more flexible than "fieldtype", this option allows you to
specify *any* type of HTML attribute and have it be the default for
all fields. For example:
my $form = CGI::FormBuilder->new(..., fieldattr => { class => 'myClass' });
Would set the "class" HTML attribute on all fields by default, so
that when they are printed out they will have a "class="myClass""
part of their HTML tag.
font => $font
The font to use for the form. This is output as a series of ""
tags for best browser compatibility. If you're thinking about using
this, check out the "template" option above (and below).
header => 1 | 0
If set to 1, a valid "Content-type" header will be printed out. As
of version 1.69, this now defaults to 0, meaning no header will be
printed unless you specifically say "header => 1".
javascript => 1 | 0
If set to 1, JavaScript is generated in addition to HTML, the
default setting.
jshead => JSCODE
If using JavaScript, you can also specify some JavaScript code that
will be included verbatim in the section of the document.
jsfunc => JSCODE
Just like "jshead", only this is stuff that will go into the
"validate" JavaScript function. As such, you can use it to add extra
JavaScript validate code verbatim. Just return false if something
doesn't work. For example:
my $jsfunc = <
[% END %]
[% field.required
? "$field.label"
: field.label
%]
[% IF field.invalid %]
Missing or invalid entry, please try again.
[% END %]
[% field.field %]
[% form.submit %]
[% END %]
If you want to customise any of the Template Toolkit options, you
can set the "engine" option to contain a reference to an existing
"Template" object or hash reference of options which are passed to
the "Template" constructor. You can also set the "data" item to
define any additional variables you want accesible when the template
is processed.
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => {
type => 'TT2',
template => 'form.html',
variable => 'form'
engine => {
INCLUDE_PATH => '/usr/local/tt2/templates',
},
data => {
version => 1.23,
author => 'Fred Smith',
},
},
);
For further details on using the Template Toolkit, see the Template
manpage or http://template-toolkit.org/ .
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 "Contact $adm
for more help", but if you want lots of text check out the
"template" option above.
title => $title
This takes a string to use as the title of the form.
values => \%hash
The "values" 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 CGI.
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.
validate => \%hash
This option takes a hashref of key/value pairs, where each key is
the name of a field from the "fields" option, and each value is one
of several things:
- 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 comparison to do
And these can also be grouped together as:
- a hashref containing pairings of comparisons to do for
the two different languages, "javascript" and "perl"
For example, you could specify the following "validate" params:
my $form = CGI::FormBuilder->new(
fields => [qw/username password confirm_password
first_name last_name email/],
validate => { username => [qw/nate jim bob/],
first_name => '/^\w+$/', # note the
last_name => '/^\w+$/', # single quotes!
email => 'EMAIL',
password => 'VALUE',
confirm_password => {
javascript => '== form.password.value',
perl => 'eq $form->field("password")'
}
}
);
This would create both JavaScript and Perl conditionals on the fly
that would ensure:
- "username" was either "nate", "jim", or "bob"
- "first_name" and "last_name" both match the regex's specified
- "email" is a valid EMAIL format
- "confirm_password" is equal to the "password" field
Any regular expressions you specify must be enclosed in single
quotes because they need to be used for both JavaScript and Perl
code. As such, specifying a "qr//" will not work. Patches welcome.
Note that for both the "javascript" and "perl" hashref code options,
the form will be present as the variable named "form". For the Perl
code, you actually get a complete $form object meaning that you have
full access to all its methods (although the "field()" method is
probably the only one you'll need for validation).
In addition to taking any regular expression you'd like, the
"validate" option also has many builtin defaults that can prove
helpful:
VALUE - is any type of non-null value
WORD - is a word (\w+)
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:\windows\system)
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
I know 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.
Note that any other options specified are passed to the "
That's all you need for a sticky search form with the above HTML layout.
Notice that you can change the HTML layout as much as you want without
having to touch your CGI code.
Ex4: user_info.cgi
This script grabs the user's information out of a database and lets them
update it dynamically. The DBI information is provided as an example,
your mileage may vary:
#!/usr/bin/perl -w
use strict;
use CGI::FormBuilder;
use DBI;
use DBD::Oracle
my $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass');
# 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/]
);
# 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;
# Render our form with the defaults we got in our hashref
print $form->render(values => $default_hashref,
title => "User information for '$user'");
FREQUENTLY ASKED QUESTIONS
There are a couple questions and subtle traps that seem to poke people
on a regular basis. Here are some hints.
I'm confused. Why doesn't field() work like CGI's param()?
If you're used to "CGI.pm", you have to do a little bit of a brain
shift when working with this module.
First, this module is designed to address fields as *abstract
entities*. That is, you don't create a "checkbox" or "radio group"
per se. Instead, you create a field named for the data you want to
collect. FormBuilder takes care of figuring out what the most
optimal HTML representation is for you.
So, if you want a single-option checkbox, simply say something like
this:
$form->field(name => 'join_mailing_list', options => 'Yes');
If you want it to be checked by default, you add the "value" arg:
$form->field(name => 'join_mailing_list', options => 'Yes',
value => 'Yes');
You see, you're creating a field that has one possible option:
"Yes". Then, you're saying its current value is, in fact, "Yes".
This will result in FormBuilder creating a single-option field
(which is a checkbox by default) and selecting the requested value
(meaning that the box will be checked).
If you want multiple values, then all you have to do is specify
multiple options:
$form->field(name => 'join_mailing_list', options => [qw/Yes No/],
value => 'Yes');
Now you'll get a radio group, and "Yes" will be selected for you! By
viewing fields as data entities (instead of HTML tags) you get much
more flexibility and less code maintenance. If you want to be able
to accept multiple values, simply add the "multiple" arg:
$form->field(name => 'favorite_colors', multiple => 1,
options => [qw/red green blue]);
Depending on the number of "options" you have, you'll get either a
set of checkboxes or a multiple select list (unless you manually
override this with the "type" arg). Regardless, though, to get the
data back all you have to say is:
my @colors = $form->field('favorite_colors');
And the rest is taken care of for you.
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 FormBuilder only knows about those fields
you've told it about. So, let's assume that you're going to use a
special parameter called "mode" to control the mode of your
application so that you can call it like this:
myapp.cgi?mode=list&...
myapp.cgi?mode=edit&...
myapp.cgi?mode=remove&...
And so on. You need to do two things. First, you need the
"keepextras" option:
my $form = CGI::FormBuilder->new(..., keepextras => 1);
This will maintain the "mode" field as a hidden field across
requests automatically. Second, you need to realize that since the
"mode" is not a defined field, you have to get it via the
"cgi_param()" method:
my $mode = $form->cgi_param('mode');
This will allow you to build a large multiscreen application easily,
even integrating it with modules like "CGI::Application" or if you
want.
You can also do this by simply defining "mode" as a field in your
"fields" declaration. The reason this is discouraged is because when
iterating over your fields you'll get "mode", which you likely don't
want (since it's not "real" data).
Why won't CGI::FormBuilder work with POST requests?
It will, but chances are you're probably doing something like this:
use CGI qw/:standard/;
use CGI::FormBuilder;
# Our "mode" parameter determines what we do
my $mode = param('mode');
# Changed our form based on our mode
if ($mode eq 'view') {
my $form = CGI::FormBuilder->new(...);
} elsif ($mode eq 'edit') {
my $form = CGI::FormBuilder->new(...);
}
The problem is this: Once you read a "POST" request, it's gone
forever. In the above code, what you're doing is having "CGI.pm"
read the "POST" request (on the first call of "param()").
Luckily, there is an easy solution. First, you need to modify your
code to use the OO form of "CGI.pm". Then, simply specify the "CGI"
object you create to the "params" option of FormBuilder:
use CGI;
use CGI::FormBuilder;
my $cgi = CGI->new;
# Our "mode" parameter determines what we do
my $mode = $cgi->param('mode');
# Changed our form based on our mode
if ($mode eq 'view') {
my $form = CGI::FormBuilder->new(params => $cgi, ...);
} elsif ($mode eq 'edit') {
my $form = CGI::FormBuilder->new(params => $cgi, ...);
}
How do I make it so that the values aren't shown in the form?
Easy.
my $form = CGI::FormBuilder->new(sticky => 0, ...);
By turning off the "sticky" option, you will still be able to access
the values but they won't show up in the form.
How do I override the value of a field?
Simple, just use:
$form->field(name => 'name_of_field', value => $value);
Note that until recently, this was totally broken. So if you're
having problems make sure you're running at least version 1.86
(which you should be if you're reading this).
How can I change option XXX based on a conditional?
Remember that "render()" can take any option that "new()" can. This
means that you can set some features on your form sooner and others
later:
my $form = CGI::FormBuilder->new(method => 'POST');
my $mode = $form->cgi_param('mode');
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 => \%values);
}
In fact, since any of the options can be used in either "new()" or
"render()", you could have specified "fields" to "new()" above since
they are the same for both conditions.
Can FormBuilder handle file uploads?
It sure can, and it's really easy too. Just change the "enctype" as
an option to "new()":
my $form = CGI::FormBuilder->new(enctype => 'multipart/form-data',
method => 'POST', fields => [qw/file/]);
And then get your file with:
my $file = $form->field('file');
In fact, that's a whole file upload program right there.
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 especially patches to fix such bugs are
welcomed.
I'm always open to entertaining "new feature" 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.
NOTES
Parameters beginning with a leading underscore are reserved for future
use by this module. Use at your own peril.
This module does a lot of guesswork for you. This means that sometimes
(although hopefully rarely), you may be scratching your head wondering
"Why did it do that?". Just use the "field" method to set things up the
way you want and move on.
FormBuilder will try to make use of "CGI::Minimal" if it is available,
as that module is much faster than "CGI.pm". It is recommended you get
it and install it!
ACKNOWLEDGEMENTS
This module has really taken off, thanks to very useful input and
encouraging feedback from a number of people, including:
Andy Wardley - huge patch enabling Template Toolkit (TT2)
Mark Belanger - lots of helpful regex additions and bugfinding
William Large - tons of debugging help and doc suggestions
Kevin Lubic - tons more debugging and encouragement
There have also been a bunch of people who have pointed out bugs and to
you I am appreciative as well.
SEE ALSO
the HTML::Template manpage, the Template manpage, the CGI::Minimal
manpage, the CGI manpage
VERSION
$Id: FormBuilder.pm,v 1.92 2001/12/12 22:00:43 nwiger Exp $
AUTHOR
Copyright (c) 2001 Nathan Wiger [% field.label %] [% field.field %]