NAME
CGI::FormBuilder - Easily generate and process stateful forms
SYNOPSIS
use CGI::FormBuilder;
# Let's assume we did a DBI query to get existing values
my $dbval = $sth->fetchrow_hashref;
my $form = CGI::FormBuilder->new(
method => 'POST',
fields => [qw/name email phone gender/],
values => $dbval,
validate => { email => 'EMAIL', phone => 'PHONE' },
required => 'ALL',
);
# Change gender field to have options
$form->field(name => 'gender', options => [qw/Male Female/]);
if ($form->submitted && $form->validate) {
my $fields = $form->field; # get form fields as hashref
# Do something to update your data (you would write this)
do_data_update($fields->{name}, $fields->{email},
$fields->{phone}, $fields->{gender});
print $form->confirm(header => 1); # confirmation screen
$form->mailconfirm(to => $fields->{email});
} else {
print $form->render(header => 1); # print out the form
}
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(<input name="email" type="text" size="20">);
# 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
(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 FormBuilder works. The basic usage is straightforward, and has these steps:
Create a new
CGI::FormBuilder
object with the proper optionsModify any fields that may need fiddling with
Validate the form, if applicable, and print it out
FormBuilder 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:
use CGI::FormBuilder;
my @fields = qw(name email password confirm_password zipcode);
my $form = CGI::FormBuilder->new(fields => \@fields);
print $form->render(header => 1);
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:
<html>
<head>
<title>User Information</title>
<tmpl_var js-head><!-- this holds the JavaScript code -->
</head>
<tmpl_var form-start><!-- this holds the initial form tag -->
<h3>User Information</h3>
Please fill out the following information:
<!-- each of these tmpl_var's corresponds to a field -->
<p>Your full name: <tmpl_var field-name>
<p>Your email address: <tmpl_var field-email>
<p>Choose a password: <tmpl_var field-password>
<p>Please confirm it: <tmpl_var field-confirm_password>
<p>Your home zipcode: <tmpl_var field-zipcode>
<p>
<tmpl_var form-submit><!-- this holds the form submit button -->
</form><!-- can also use "tmpl_var form-end", same thing -->
Then, all you need to do in your Perl is add the template
option:
my $form = CGI::FormBuilder->new(fields => \@fields,
validate => {email => 'EMAIL'},
template => 'userinfo.tmpl');
And the rest of the code stays the same.
You can also do a similar thing using the Template Toolkit (http://template-toolkit.org/) to generate the form. This time, specify the template
option as a hashref which includes the type
option set to TT2
and the template
option to denote the name of the template you want processed. You can also add variable
as an option (among others) to denote the variable name that you want the form data to be referenced by.
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => {
type => 'TT2',
template => 'userinfo.tmpl',
variable => 'form',
}
);
The template might look something like this:
<html>
<head>
<title>User Information</title>
[% form.jshead %]
</head>
<body>
[% form.start %]
<table>
[% FOREACH field = form.fields %]
<tr valign="top">
<td>
[% field.required
? "<b>$field.label</b>"
: field.label
%]
</td>
<td>
[% IF field.invalid %]
Missing or invalid entry, please try again.
<br/>
[% END %]
[% field.field %]
</td>
</tr>
[% END %]
<tr>
<td colspan="2" align="center">
[% form.submit %]
</td>
</tr>
</table>
[% form.end %]
</body>
</html>
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.tmpl',
header => 1
);
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);
# 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 if 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 could change the formatting based on whether layout
appeared in the query string:
my $form = CGI::FormBuilder->new(method => 'POST',
fields => [qw/name email/]);
# Get our layout from an extra CGI param
my $layout = $form->cgi_param('layout');
# 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);
}
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
<body>
tag verbatim (for example, bgcolor, alink, etc). If you're thinking about using this, check out thetemplate
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 | \%hash
-
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.You can also specify a hashref of key/value pairs. The advantage is you can then bypass the
values
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 tofields
is not very useful. - 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
by default. Easy:my $form = CGI::FormBuilder->new(... 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 aclass="myClass"
part of their HTML tag. - font => $font
-
The font to use for the form. This is output as a series of
<font>
tags for best browser compatibility. If you're thinking about using this, check out thetemplate
option. - header => 1 | 0
-
If set to 1, a valid
Content-type
header will be printed out. This defaults to 0, since usually people end up using templates or embedding forms in other HTML. - 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 <head> section of the document.
- jsfunc => JSCODE
-
Just like
jshead
, only this is stuff that will go into thevalidate
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 = <<EOF; if (form.password.value == 'password') { alert("What are you, a moron? You used 'password' for your password?!"); return false; } EOF ->new(... jsfunc => $jsfunc);
This is another option I don't like. Should you be using a template?
- keepextras => 1 | 0
-
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
cgi_param()
, notfield()
, to get to the values. This is useful if you want to keep some extra parameters like referrer or company available but not have them be valid form fields. See below under/"param"
for more details. - labels => \%hash
-
Like
values
, this is a list of key/value pairs where the keys are the names offields
specified above. By default, FormBuilder 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.For example:
my $form = CGI::FormBuilder->new( fields => [qw/name email/], labels => { name => 'Your Full Name', email => 'Primary Email Address' } );
Usually you'll find that if you're contemplating this option what you really want is a template.
- 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.
- linebreaks => 1 | 0
-
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.
- method => 'POST' | 'GET'
-
Either
POST
orGET
, the type of CGI method to use. Defaults toGET
if nothing is specified. - name => $string
-
This option can only be specified to
new()
but not torender()
.This names the form. It is optional, but if you specify it you must do so in
new()
since the name is then used to alter how variables are created and looked up.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.
- params => $object
-
This option can only be specified to
new()
but not torender()
.This specifies an object from which the parameters should be derived. The object must have a
param()
method which will return values for each parameter by name. By default a CGI object will be automatically created and used.However, you will want to specify this if you're using
mod_perl
:use Apache::Request; use CGI::FormBuilder; sub handler { my $r = Apache::Request->new(shift); my $form = CGI::FormBuilder->new(... params => $r); # ... print $form->render; }
Or, if you need to initialize a
CGI.pm
object separately and are using aPOST
form method:use CGI; use CGI::FormBuilder; my $q = new CGI; my $mode = $q->param('mode'); # do stuff based on mode ... my $form = CGI::FormBuilder->new(... params => $q);
The above example would allow you to access CGI parameters directly via
$q->param
(however, note that you could get the same functionality by using$form->cgi_param
). - 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
required
option is not specified, by default any fields named invalidate
will be required.As of v1.97, the
required
option now takes two other settings, the stringALL
and the stringNONE
. If you specifyALL
, then all fields are required. If you specifyNONE
, then none of them are in spite of what may be set via the "validate" option.This is useful if you have fields that you need to be validated if filled in, but which are optional. For example:
my $form = CGI::FormBuilder->new( fields => qw[/name email/], validate => { email => 'EMAIL' }, required => 'NONE' );
This would make the
email
field optional, but if filled in then it would have to match theEMAIL
pattern.In addition, it is very important to note that if the
required
andvalidate
options are specified, then they are taken as an intersection. That is, only those fields specified asrequired
must be filled in, and the rest are optional. For example:my $form = CGI::FormBuilder->new( fields => qw[/name email/], validate => { email => 'EMAIL' }, required => [qw/name/] );
This would make the
name
field mandatory, but theemail
field optional. However, ifemail
is filled in, then it must match the builtinEMAIL
pattern. - reset => 0 | $string
-
If set to 0, then the "Reset" 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 "Reset".
- selectnum => $threshold
-
These affect the "intelligence" of the module. If a given field has any options, then it will be a radio group by default. However, if more than
selectnum
options are present, then it will become a select list. The default is 5 or more options. For example:# This will be a radio group my @opt = qw(Yes No); $form->field(name => 'answer', options => \@opt); # However, this will be a select list my @states = qw(AK CA FL NY TX); $form->field(name => 'state', options => \@states); # This is the one special case - single items are checkboxes $form->field(name => 'answer', options => 'Yes');
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
multiple => 1
to thefield()
method. Got it? - smartness => 0 | 1 | 2
-
By default CGI::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
smartness
to0
. If you want it to be really smart, like figuring out what type of validation routines to use for you, set it to2
. It defaults to1
. - static => 1 | 0
-
If set to 1, then the form will be output with static hidden fields. Defaults to 0.
- sticky => 1 | 0
-
Determines whether or not form values should be sticky across submissions. This does not affect the value you get back from a call to
field()
. It also does not affect default values. It only affects values the user may have entered via the CGI.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 "EXAMPLES" section for a good example.
- submit => 0 | $string | \@array
-
If set to 0, then the "Submit" button is not printed. It defaults to creating a button that says "Submit" verbatim. If given an argument, then that argument becomes the text to show. For example:
print $form->render(submit => 'Do Lookup');
Would make it so the submit button says "Do Lookup" on it.
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 CGI via some JavaScript tricks. So this:
print $form->render(submit => ['Add A Gift', 'No Thank You']);
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
submitted()
function:my $clicked = $form->submitted;
So if the user clicked "Add A Gift" then that is what would end up in the variable
$clicked
above. This allows nice conditionality:if ($form->submitted eq 'Add A Gift') { # show the gift selection screen } elsif ($form->submitted eq 'No Thank You') # just process the form }
See the "EXAMPLES" section for more details.
- table => 1 | 0
-
By default FormBuilder decides how to layout the form based on the number of fields, values, etc. You can force it into a table by specifying
1
, or force it out of one with0
. I have never found this option useful. - template => $filename | \%hash
-
This points to a filename that contains an
HTML::Template
compatible template to use to layout the HTML. You can also specify thetemplate
option as a reference to a hash, allowing you to further customize the template processing options.For example, you could turn on caching in
HTML::Template
with something like the following:my $form = CGI::FormBuilder->new( fields => \@fields, template => { filename => 'form.tmpl', die_on_bad_params => 0, # required shared_cache => 1 } );
In addition, specifying a hashref allows you to use an alternate template processing system like the
Template Toolkit
. A minimal configuration would look like this:my $form = CGI::FormBuilder->new( fields => \@fields, template => { type => 'TT2', # use Template Toolkit template => 'form.tmpl', }, );
The
type
option specifies the name of the processor. UseTT2
to invoke the Template Toolkit orHTML
(the default) to invokeHTML::Template
as shown above. All other options besidestype
are passed to the constructor for that templating system verbatim, so you'll need to consult those docs to see what different options do.For lots more information on templates, see the "TEMPLATES" section below.
- 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.
- 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 "middle".
- values => \%hash | \@array
-
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. The values are used case-insensitively, making it easier to use DBI hashref records (which are in upper or lower case depending on your database).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:
my $rec = $sth->fetchrow_hashref; my $form = CGI::FormBuilder->new(fields => \@fields, values => $rec);
As of version 1.95, you can also pass an arrayref, in which case each value is used sequentially for each field as specified to the
fields
option. - 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 each of these can also be grouped together as:
- a hashref containing pairings of comparisons to do for the two different languages, "javascript" and "perl"
By default, the
validate
option also sets up each field so that it is required. However, if you specify therequired
option, then only those fields explicitly listed would be required, and the rest would only be validated if filled in. See therequired
option for more details.Let's look at a concrete example:
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 => '/^\S{6,8}$/', 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.Note that for both the
javascript
andperl
hashref code options, the form will be present as the variable namedform
. For the Perl code, you actually get a complete$form
object meaning that you have full access to all its methods (although thefield()
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 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.
Note that any other options specified are passed to the <form>
tag verbatim. For example, you could specify onSubmit
or enctype
to add the respective attributes.
field(name => $name, opt => $val, opt => $val)
This method is called on the $form
object you get from the new()
method above, and is used to manipulate individual fields. You can use this if you want to specify something is a certain type of input, or has a certain set of options.
For example, let's say that you create a new form:
my $form = CGI::FormBuilder->new(fields => [qw/name state zip/]);
And that you want to make the "state" field a select list of all the states. You would just say:
$form->field(name => 'state', type => 'select',
options => \@states);
Then, when you used render()
to create the form output, the "state" field would appear as a select list with the values in @states
as options.
If just given the name
argument and no other options, then the value of that field will be returned:
my $email = $form->field(name => 'email');
Like CGI.pm's param()
, in this form the name =>
is optional:
my $email = $form->field('email');
Why is this not named param()
? Simple: Because it's not compatible. Namely, while the return context behavior is the same, this function is not responsible for retrieving all CGI parameters - only those defined as valid form fields. This is important, as it allows your script to accept only those field names you've defined for security.
To get the list of valid field names just call it without and args:
my @fields = $form->field;
And to get a hashref of field/value pairs, call it as:
my $fields = $form->field;
my $name = $fields->{name};
Note that if you call it as a hashref, you will only get one single value per field. This is just fine as long as you don't have multiple values per field (the normal case). However, if you have a query string like this:
favorite_colors.cgi?color=red&color=white&color=blue
Then you will only get one value for color
in the hashref. In this case you'll need to access it via field()
to get them all:
my @colors = $form->field('color');
The field()
function takes several parameters, the first of which is mandatory. The rest are listed in alphabetical order:
- name => $name
-
The name of the field to manipulate. The "name =>" part is optional if there's only one argument. For example:
my $email = $form->field(name => 'email'); my $email = $form->field('email'); # same thing
However, if you're specifying more than one argument then you must include the
name
part:$form->field(name => 'email', size => '40');
- comment => $string
-
This prints out the given comment after the field to fill in, vebatim. For example, if you wanted a field to look like this:
Joke [____________] (keep it clean, please!)
You would use the following:
$form->field(name => 'joke', comment => '(keep it clean, please!)');
The
comment
can actually be anything you want (even another form field). But don't tell anyone I said that. - force => 1 | 0
-
This is used in conjunction with the
value
option to forcibly override a field's value. See below under thevalue
option for more details. - jsclick => $jscode
-
This is a simple abstraction over directly specifying the JavaScript action type. This turns out to be extremely useful, since if an option list changes from
select
toradio
orcheckbox
(depending on the number of options), then the action changes fromonChange
toonClick
. Why?!?!So if you said:
$form->field(name => 'credit_card', jsclick => 'recalc_total();', options => \@cards)
This would generate the following code, depending on the number of
@cards
:<select name="credit_card" onChange="recalc_total();"> ... <radio name="credit_card" onClick="recalc_total();"> ...
You get the idea.
- label => $string
-
This will be the label printed out next to the field. By default it will be generated automatically from the field name.
- labels => \%hash
-
This takes a hashref of key/value pairs where each key is one of the options, and each value is what its printed label should be. For example:
$form->field(name => 'state', options => [qw/AZ CA NV OR WA/], labels => { AZ => 'Arizona', CA => 'California', NV => 'Nevada', OR => 'Oregon', WA => 'Washington });
When rendered, this would create a select list where the option values were "CA", "NV", etc, but where the state's full name was displayed for the user to select.
You can also get the same effect by passing complex data structures directly to the
options
argument (see below). If you have predictable data, check out thenameopts
option. - multiple => 1 | 0
-
If set to 1, then the user is allowed to choose multiple values from the options provided. This turns radio groups into checkboxes and selects into multi-selects. Defaults to automatically being figured out based on number of values.
- nameopts => 1 | 0
-
If set to 1, then options for select lists will be automatically named just like the fields. So, if you specified a list like:
$form->field(name => 'department', options => qw[/molecular_biology philosophy psychology particle_physics social_anthropology/], nameopts => 1);
This would create a list like:
<select name="department"> <option value="molecular_biology">Molecular Biology</option> <option value="philosophy">Philosophy</option> <option value="psychology">Psychology</option> <option value="particle_physics">Particle Physics</option> <option value="social_anthropology">Social Anthropology</option> </select>
Basically, you get names for the options that are determined in the same way as the names for the fields. This is designed as a simpler alternative to using custom
options
data structures if your data is regular enough to support it. - options => \@options | \%options
-
This takes an arrayref of options. It also automatically results in the field becoming a radio (if <= 4) or select list (if > 4), unless you explicitly set the type with the
type
parameter.Each item will become both the value and the text label by default. That is, if you specified these options:
$form->field(name => 'opinion', options => [qw/yes no maybe so/]);
You will get something like this:
<select name="opinion"> <option value="yes">yes</option> <option value="no">no</option> <option value="maybe">maybe</option> <option value="so">so</option> </select>
However, if a given item is either an arrayref or hashref, then the first element will be taken as the value and the second as the label. So something like this:
push @opt, ['yes', 'You betcha!']; push @opt, ['no', 'No way Jose']; push @opt, ['maybe', 'Perchance...']; push @opt, ['so', 'So']; $form->field(name => 'opinion', options => \@opt);
Would result in something like the following:
<select name="opinion"> <option value="yes">You betcha!</option> <option value="no">No way Jose</option> <option value="maybe">Perchance...</option> <option value="so">So</option> </select>
And this code would have the same effect:
push @opt, { yes => 'You betcha!' }; push @opt, { no => 'No way Jose' }; push @opt, { maybe => 'Perchance...' }; push @opt, { so => 'So' }; $form->field(name => 'opinion', options => \@opt);
As would, in fact, this code:
my %opt = ( yes => 'You betcha!', no => 'No way Jose', maybe => 'Perchance...', so => 'So' ); $form->field(name => 'opinion', options => \%opt);
You get the idea. The goal is to give you as much flexibility as possible when constructing your data structures, and this module figures it out correctly. The only disadvantage to the very last method is that since the top-level structure is a hash, you cannot control the order of the options.
If you're just looking for simple naming, see the
nameopts
option above. - required => 1 | 0
-
If set to 1, the field must be filled in. These two are the same:
$form->field(name => 'email', required => 1); $form->field(name => 'email', validate => 'VALUE');
- sortopts => alpha | numeric
-
If set, and there are options, then the options will be sorted in the specified order. For example:
$form->field(name => 'category', options => \@cats, sortopts => 'alpha');
Would sort the
@cats
options in alpha order. - type => $type
-
Type of input box to make it. Default is "text", and valid values include anything allowed by the HTML specs, including "password", "select", "radio", "checkbox", "textarea", "hidden", and so on.
If set to "static", then the field will be printed out, but will not be editable. Like when you print out a complete static form, the field's value will be placed in a hidden field as well.
- value => $value | \@values
-
The
value
option can take either a single value or an arrayref of multiple values. In the case of multiple values, this will result in the field automatically becoming a multiple select list or checkbox group, depending on the number of options specified above.Just like the 'values' to
new()
, this can be overridden by CGI values. To forcibly change a value, you need to specify theforce
option described above, for example:$form->field(name => 'credit_card', value => 'not shown', force => 1);
This would make the
credit_card
field into "not shown", useful for hiding stuff if you're going to usemailresults()
. - validate => '/regex/'
-
Similar to the
validate
option used innew()
, this affects the validation just of that single field. As such, rather than a hashref, you would just specify the regex to match against.This regex must be specified as a single-quoted string, and NOT as a qr() regex. The reason is that this needs to be easily usable by JavaScript routines as well.
- [htmlattr] => $value, [htmlattr] => $value
-
In addition to the above tags, the
field()
function can take any other valid HTML attribute, which will be placed in the tag verbatim. For example, if you wanted to alter the class of the field (if you're using stylesheets and a template, for example), you could say:$form->field(name => 'email', class => 'FormField', size => 80);
Then when you call
$form-
render> you would get a field something like this:<input type="text" name="email" class="FormField" size="80">
(Of course, for this to really work you still have to create a class called
FormField
in your stylesheet.)See also the
fieldattr
option which can be passed to eithernew()
orrender()
and which provides global defaults for all fields.
cgi_param(opt => $val, opt => $val)
Wait a second, if we have field()
from above, why the heck would we ever need cgi_param()
?
Simple. The above field()
function does a bunch of special stuff. For one thing, it will only return fields which you have explicitly defined in your form. Excess parameters will be silently ignored. Also, it will incorporate defaults you give it, meaning you may get a value back even though the user didn't enter one explicitly in the form (see above).
But, you may have some times when you want extra stuff so that you can maintain state, but you don't want it to appear in your form. B2B and branding are easy examples:
http://hr-outsourcing.com/newuser.cgi?company=mr_propane
This could change stuff in your form so that it showed the logo and company name for the appropriate vendor, without polluting your form parameters.
This call simply redispatches to CGI::Minimal
(if installed) or CGI.pm
's param()
methods, so consult those docs for more information.
tmpl_param(name => $val)
This allows you to interface with your HTML::Template
template, if you are using one. As with cgi_param()
above, this is only useful if you're manually setting non-field values. FormBuilder will automatically setup your field parameters for you; see the "template" option for more details.
confirm()
The purpose of this function is to print out a static confirmation screen showing a short message along with the values that were submitted. This takes a single option - text
- which does the same thing listed above.
submitted('fieldname')
This returns the value of the "Submit" button if the form has been submitted, undef otherwise. This allows you to either test it in a boolean context:
if ($form->submitted) { ... }
Or to retrieve the button that was actually clicked on in the case of multiple submit buttons:
if ($form->submitted eq 'Update') {
...
} elsif ($form->submitted eq 'Delete') {
...
}
It's best to call validate()
in conjunction with this to make sure the form validation works. To make sure you're getting accurate info, it's recommended that you name your forms with the name
option described above.
If you're writing a multiple-form app, you should name your forms with the 'name' option to ensure that you are getting an accurate return value from this sub. See the 'name' option above, under render()
.
You can also specify the name of an optional field which you want to "watch" instead of the default _submitted
hidden field. This is useful if you have a search form and also want to be able to link to it from other documents directly, such as:
mysearch.cgi?lookup=what+to+look+for
Normally, submitted()
would return false since the _submitted
field is not included. However, you can override this by saying:
$form->submitted('lookup');
Then, if the lookup field is present, you'll get a true value. (Actually, you'll still get the value of the "Submit" button if present.)
validate(field => '/regex/', field => '/regex/')
This validates the form based on the validation criteria passed into new()
via the validate
option. In addition, you can specify additional criteria to check that will be valid for just that call of validate()
. This is useful is you have to deal with different geos:
if ($location eq 'US') {
$form->validate(state => 'STATE', zipcode => 'ZIPCODE');
} else {
$form->validate(state => '/^\w{2,3}$/');
}
Note that if you pass args to your validate()
function like this, you will not get JavaScript generated or required fields placed in bold. So, this is good for conditional validation like the above example, but for most applications you want to pass your validation requirements in via the validate
parameter to the new()
function.
mailconfirm(to => $email, from => $email, cc => $email, subject => $string, text => $string);
This sends a confirmation email to the named addresses. The to
argument is required; everything else is optional. If no from
is specified then it will be set to the address auto-reply
since that is a common quasi-standard in the web app world.
This does not send any of the form results. Rather, it simply prints out a message saying the submission was received.
mailresults(to => $email, delimiter => $delim, joiner => $join, subject => $string);
This emails the form results to the specified address(es). By default it prints out the form results separated by a colon, such as:
name: Nathan Wiger
email: nate@wiger.org
colors: red green blue
And so on. You can change this by specifying the delimiter
and joiner
options. For example this:
$form->mailresults(to => $to, delimiter => '=', joiner => ',');
Would produce an email like this:
name=Nathan Wiger
email=nate@wiger.org
colors=red,green,blue
Note that now the last field ("colors") is separated by commas since you have multiple values and you specified a comma as your joiner
.
mail(opt => $val, opt => $val)
This is a more generic version of the above; it sends whatever is given as the text
argument via email verbatim to the to
address. In addition, if you're not running sendmail
you can specify the mailer
parameter to give the path of your mailer. This option is accepted by the above functions as well.
sessionid($id)
This gets and sets the sessionid, which is stored in the special form field _sessionid
. By default no session ids are generated or used. Rather, this is intended to provide a hook for you to easily integrate this with a session id module like Apache::Session
.
Since you can set the session id via the _sessionid
field, you can pass it as an argument when first showing the form:
http://mydomain.com/forms/update_info.cgi?_sessionid=0123-091231
This would set things up so that if you called:
my $id = $form->sessionid;
This would set $id
to 0123-091231
in your script.
TEMPLATES
FormBuilder has the ability to "drive" both HTML::Template
and Template Toolkit
. You enable a template by specifying the template
option and passing it the appropriate information. Then, you must place special tags in your template which will be expanded for you. Let's look at each template solution in turn.
HTML::Template
HTML::Template
is the default template option and is activated one of two ways. Either:
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => $filename
);
Or, you can specify any options which HTML::Template->new
accepts by using a hashref:
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => {
filename => $filename,
die_on_bad_params => 0,
shared_cache => 1,
loop_context_vars => 1
}
);
When using HTML::Template
, many different <tmpl_var>
variables are provided for you. For this reason, it is required that you set the die_on_bad_params
option to 0
if specifying a hashref. This is done for you automatically if you just specify a filename.
In your template, each of the form fields will correspond directly to a <tmpl_var>
of the same name prefixed with "field-" in the template. So, if you defined a field called "email", then you would setup a variable called <tmpl_var field-email>
in your template, and this would be expanded to the complete HTML <input>
tag.
In addition, there are a couple special fields:
<tmpl_var js-head> - JavaScript to stick in <head>
<tmpl_var form-start> - Opening <form> tag w/ options
<tmpl_var form-submit> - The submit button(s)
<tmpl_var form-reset> - The reset button
<tmpl_var form-end> - Just the closing </form> tag
So, let's revisit our userinfo.tmpl
template from above:
<html>
<head>
<title>User Information</title>
<tmpl_var js-head><!-- this holds the JavaScript code -->
</head>
<tmpl_var form-start><!-- this holds the initial form tag -->
<h3>User Information</h3>
Please fill out the following information:
<!-- each of these tmpl_var's corresponds to a field -->
<p>Your full name: <tmpl_var field-name>
<p>Your email address: <tmpl_var field-email>
<p>Choose a password: <tmpl_var field-password>
<p>Please confirm it: <tmpl_var field-confirm_password>
<p>Your home zipcode: <tmpl_var field-zipcode>
<p>
<tmpl_var form-submit><!-- this holds the form submit button -->
</form><!-- can also use "tmpl_var form-end", same thing -->
As you see, you get a <tmpl_var>
for each for field you define.
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 a <tmpl_var>
with the prefix "value-" in your template. This will only contain the field's value. So:
For the field... The <input> tag is in Just the value is in
---------------- ---------------------- ----------------------
job <tmpl_var field-job> <tmpl_var value-job>
size <tmpl_var field-size> <tmpl_var value-size>
email <tmpl_var field-email> <tmpl_var value-email>
This means you could say something like this in your template:
<input type="text" name="email" value="<tmpl_var value-email>">
And FormBuilder would take care of the value stickiness for you, while you have control over the specifics of the <input>
tag.
Note, though, that this will only get the first 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 <tmpl_var>
prefixed with "loop-". So, if you had:
myapp.cgi?color=gray&color=red&color=blue
This would give the color
field three values. To create a select list, you would do this in your template:
<select name="color" multiple>
<tmpl_loop loop-color>
<option value="<tmpl_var value>"><tmpl_var label></option>
</tmpl_loop>
</select>
With <tmpl_loop>
tags, each iteration gives you several variables:
Inside <tmpl_loop>, this... Gives you this
--------------------------- -------------------------------
<tmpl_var value> value of that option
<tmpl_var label> label for that option
<tmpl_var checked> if selected, the word "checked"
<tmpl_var selected> if selected, the word "selected"
Please note that <tmpl_var value>
gives you one of the options, 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.
When you need precise control in a template this is all exposed to you; normally FormBuilder does all this magic for you. If you don't need exact control over your lists, simply use the <tmpl_var field-XXX>
tag and this will all be done automatically, which I strongly recommend.
But, let's assume you need exact control over your lists. Here's an example select list template:
<select name="color" multiple>
<tmpl_loop loop-color>
<option value="<tmpl_var value>" <tmpl_var selected>><tmpl_var label>
</tmpl_loop>
</select>
Then, your Perl code would fiddle the field as follows:
$form->field(name => 'color', nameopts => 1,
options => [qw/red green blue yellow black white gray/]);
Assuming query string as shown above, the template would then be expanded to something like this:
<select name="color" multiple>
<option value="red" selected>Red
<option value="green" >Green
<option value="blue" selected>Blue
<option value="yellow" >Yellow
<option value="black" >Black
<option value="white" >White
<option value="gray" selected>Gray
</select>
Notice that the <tmpl_var selected>
tag is expanded to the word "selected" when a given option is present as a value as well (i.e., via the CGI query). The <tmpl_var value>
tag expands to each option in turn, and <tmpl_var label>
is expanded to the label for that value. In this case, since nameopts
was specified to field()
, the labels are automatically generated from the options.
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:
Do you want to be on our mailing list?
<p><table>
<tmpl_loop loop-mailopt>
<td bgcolor="silver">
<input type="radio" name="mailopt" value="<tmpl_var value>">
</td>
<td bgcolor="white"><tmpl_var label></td>
</tmpl_loop>
</table>
Then, we would twiddle our mailopt
field via field()
:
$form->field(name => 'mailopt', options => [qw/1 0/],
labels => {
1 => 'Yes, please keep me on it!',
0 => 'No, remove me immediately.'
});
When the template is rendered, the result would be something like this:
Do you want to be on our mailing list?
<p><table>
<td bgcolor="silver">
<input type="radio" name="mailopt" value="1">
</td>
<td bgcolor="white">Yes, please keep me on it!</td>
<td bgcolor="silver">
<input type="radio" name="mailopt" value="0">
</td>
<td bgcolor="white">No, remove me immediately</td>
</table>
When the form was then sumbmitted, you would access the values just like any other field:
if ($form->field('mailopt')) {
# is 1, so add them
} else {
# is 0, remove them
}
For more information on templates, see HTML::Template.
Template Toolkit
Thanks to a huge patch from Andy Wardley, FormBuilder also supports Template Toolkit
. This is enabled by specifying the following options as a hashref to the template
argument:
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => {
type => 'TT2', # use Template Toolkit
template => 'form.tmpl'
}
);
By default, the Template Toolkit makes all the form and field information accessible through simple variables.
[% jshead %] - JavaScript to stick in <head>
[% start %] - Opening <form> tag w/ options
[% submit %] - The submit button(s)
[% reset %] - The reset button
[% end %] - Closing </form> tag
[% fields %] - List of fields
[% field %] - Hash of fields (for lookup by name)
You can specify the variable
option to have all these variables accessible under a certain namespace. For example:
my $form = CGI::FormBuilder->new(
fields => \@fields,
template => {
type => 'TT2',
template => 'form.tmpl',
variable => 'form'
},
);
With variable
set to form
the variables are accessible as:
[% form.jshead %]
[% form.start %]
etc.
You can access individual fields via the field
variable.
For a field named... The field data is in...
-------------------- -----------------------
job [% form.field.job %]
size [% form.field.size %]
email [% form.field.email %]
Each field contains various elements. For example:
[% 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 value
[% myfield.options %] # list of all values
[% myfield.required %] # required flag
[% myfield.invalid %] # invalid flag
The fields
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:
[% FOREACH field = form.fields %]
<tr>
<td>[% field.label %]</td> <td>[% field.field %]</td>
</tr>
[% 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.tmpl',
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 Template or http://template-toolkit.org/ .
EXAMPLES
I find this module incredibly useful, so here are even more examples, pasted from sample code that I've written:
Ex1: order.cgi
This example provides an order form complete with validation of the important fields.
#!/usr/bin/perl -w
use strict;
use CGI::FormBuilder;
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);
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'}
);
$form->field(name => 'state', options => \@states, sort => 'alpha');
# This adds on the 'details' field to our form dynamically
$form->field(name => 'details', cols => '50', rows => '10');
# try to validate it first
if ($form->submitted && $form->validate) {
# ... more code goes here to do stuff ...
print $form->confirm;
} else {
print $form->render;
}
This will create a form called "Order Info" that will provide a pulldown menu for the "state", a textarea for the "details", and normal text boxes for the rest. It will then validate the fields specified to the validate
option appropriately.
Ex2: order_form.cgi
This is very similar to the above, only it uses the smartness
option to fill in the "state" options automatically, as well as guess at the validation types we want. I recommend you use the debug
option to see what's going on until you're sure it's doing what you want.
#!/usr/bin/perl -w
use strict;
use CGI::FormBuilder;
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/],
);
# This adds on the 'details' field to our form dynamically
$form->field(name => 'details', cols => '50', rows => '10');
# try to validate it first
if ($form->submitted && $form->validate) {
# ... more code goes here to do stuff ...
print $form->confirm;
} else {
print $form->render;
}
Since we didn't specify the title
option, it will be automatically determined from the name of the executable. In this case it will be "Order Form".
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.
#!/usr/bin/perl -w
use strict;
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(
header => 1, template => 'ticket_search.tmpl',
fields => [qw/type string status category/]
);
# Need to setup some specific field options
$form->field(name => 'type',
options => [qw/ticket requestor hostname sysadmin/]);
$form->field(name => 'status', type => 'radio', value => 'incomplete',
options => [qw/incomplete recently_completed all/]);
$form->field(name => 'category', type => 'checkbox',
options => [qw/server network desktop printer/]);
# Render the form and print it out so our submit button says "Search"
print $form->render(submit => ' Search ');
Then, in our ticket_search.tmpl
HTML file, we would have something like this:
<html>
<head>
<title>Search Engine</title>
<tmpl_var js-head>
</head>
<body bgcolor="white">
<center>
<p>
Please enter a term to search the ticket database. Make sure
to "quote phrases".
<p>
<tmpl_var form-start>
Search by <tmpl_var field-type> for <tmpl_var field-string>
<tmpl_var form-submit>
<p>
Status: <tmpl_var field-status>
<p>
Category: <tmpl_var field-category>
<p>
</form>
</body>
</html>
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'",
header => 1);
Ex5: add_part.cgi
This presents a screen for users to add parts to an inventory database. Notice how it makes use of the sticky
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.
#!/usr/bin/perl -w
use strict;
use CGI::FormBuilder;
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 => '/^\d{3}-\d{4}-\d{4}$/',
pn => '/^\d{3}-\d{4}$/',
qty => 'INT' },
font => 'arial,helvetica'
);
# shrink the qty field for prettiness, lengthen model
$form->field(name => 'qty', size => 4);
$form->field(name => 'model', size => 60);
if ($form->submitted) {
if ($form->validate) {
# Add part to database
} else {
# Invalid; show form and allow corrections
print $form->render(sticky => 1);
exit;
}
}
# Print form for next part addition.
print $form->render;
With the exception of the database code, that's the whole application.
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
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, ...);
}
Or, since FormBuilder gives you a cgi_param()
function, you could modify your code so you use FormBuilder exclusively.
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.
I can't get "validate" to accept my regular expressions!
You're probably not specifying them within single quotes. See the section on validate
above.
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/]);
$form->field(name => 'file', type => 'file');
And then get your file with:
if ($form->submitted) {
my $file = $form->field('file');
# save contents in file, etc ...
}
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!
The output of the HTML generated natively may change slightly from release to release. If you need precise control, use a template.
ACKNOWLEDGEMENTS
This module has really taken off, thanks to very useful input, bug reports, and encouraging feedback from a number of people, including:
Andy Wardley
Mark Belanger
Jakob Curdes
Mark Houliston
William Large
Kevin Lubic
Shawn Poulson
John Theus
Thanks!
SEE ALSO
HTML::Template, Template, CGI::Minimal, CGI, CGI::Application
VERSION
$Id: FormBuilder.pm,v 2.5 2002/02/21 23:26:54 nwiger Exp $
AUTHOR
Copyright (c) 2001 Nathan Wiger <nate@wiger.org>. All Rights Reserved.
This module is free software; you may copy this under the terms of the GNU General Public License, or the Artistic License, copies of which should have accompanied your Perl kit.
2 POD Errors
The following errors were encountered while parsing the POD:
- Around line 3393:
You forgot a '=back' before '=head2'
- Around line 3585:
=back without =over