CGI::FormBuilder(3)
π CGI::FormBuilder(3) β Easily generate and process stateful forms π
User Contributed Perl Documentation, but make it group chat. Okay so bestie, this is CGI::FormBuilder(3), and we're about to make stateful forms feel less like a chore and more like a slay. β¨
π NAME π
CGI::FormBuilder β Easily generate and process stateful forms
β¨ SYNOPSIS β¨
okay so here's the whole vibe in code. Don't panic, bestie β this is literally the entire flow:
use CGI::FormBuilder;
# Assume we did a DBI query to get existing values
my $dbval = $sth->fetchrow_hashref;
# First create our form
my $form = CGI::FormBuilder->new(
name => 'acctinfo',
method => 'post',
stylesheet => '/path/to/style.css',
values => $dbval, # defaults
);
# Now create form fields, in order
# FormBuilder will automatically determine the type for you
$form->field(name => 'fname', label => 'First Name');
$form->field(name => 'lname', label => 'Last Name');
# Setup gender field to have options
$form->field(name => 'gender',
options => [qw(Male Female)] );
# Include validation for the email field
$form->field(name => 'email',
size => 60,
validate => 'EMAIL',
required => 1);
# And the (optional) phone field
$form->field(name => 'phone',
size => 10,
validate => '/^1?-?\d{3}-?\d{3}-?\d{4}$/',
comment => '<i>optional</i>');
# Check to see if we're submitted and valid
if ($form->submitted && $form->validate) {
# Get form fields as hashref
my $field = $form->fields;
# Do something to update your data (you would write this)
do_data_update($field->{lname}, $field->{fname},
$field->{email}, $field->{phone},
$field->{gender});
# Show confirmation screen
print $form->confirm(header => 1);
} else {
# Print out the form
print $form->render(header => 1);
}
πΈ DESCRIPTION πΈ
If this is your first time using FormBuilder, bestie, you should check out the website for tutorials and examples at http://formbuilder.org. π«Ά
You should also consider joining the google group at http://groups.google.com/group/perl-formbuilder. There are some pretty smart people on the list that can help you out. No cap.
π¦ 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 haven't really 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 CGI.pm are great for decoding parameters, but not for generating and processing whole forms.
The goal of CGI::FormBuilder (FormBuilder) is to provide an easy way for you to generate and process entire CGI form-based applications. Its main features are:
π§ Field Abstraction
Viewing fields as entities (instead of just params), where the HTML representation, CGI values, validation, and so on are properties of each field.
πͺ DWIMmery
Lots of built-in "intelligence" (such as automatic field typing), giving you about a 4:1 ratio of the code it generates versus what you have to write.
π₯ Built-in Validation
Full-blown regex validation for fields, even including JavaScript code generation.
π Template Support
Pluggable support for external template engines, such as HTML::Template, Text::Template, Template Toolkit, and CGI::FastTemplate.
Plus, the native HTML generated is valid XHTML 1.0 Transitional. π
π Quick Reference π
For the incredibly impatient, here's the quickest reference you can get:
# Create form
my $form = CGI::FormBuilder->new(
# Important options
fields => \@array | \%hash, # define form fields
header => 0 | 1, # send Content-type?
method => 'post' | 'get', # default is get
name => $string, # namespace (recommended)
reset => 0 | 1 | $str, # "Reset" button
submit => 0 | 1 | $str | \@array, # "Submit" button(s)
text => $text, # printed above form
title => $title, # printed up top
required => \@array | 'ALL' | 'NONE', # required fields?
values => \%hash | \@array, # from DBI, session, etc
validate => \%hash, # automatic field validation
# Lesser-used options
action => $script, # not needed (loops back)
cookies => 0 | 1, # use cookies for sessionid?
debug => 0 | 1 | 2 | 3, # gunk into error_log?
fieldsubs => 0 | 1, # allow $form->$field()
javascript => 0 | 1 | 'auto', # generate JS validate() code?
keepextras => 0 | 1 | \@array, # keep non-field params?
params => $object, # instead of CGI.pm
sticky => 0 | 1, # keep CGI values "sticky"?
messages => $file | \%hash | $locale | 'auto',
template => $file | \%hash | $object, # custom HTML
# HTML formatting and JavaScript options
body => \%attr, # {background => 'black'}
disabled => 0 | 1, # display as grayed-out?
fieldsets => \@arrayref # split form into <fieldsets>
font => $font | \%attr, # 'arial,helvetica'
jsfunc => $jscode, # JS code into validate()
jshead => $jscode, # JS code into <head>
linebreaks => 0 | 1, # put breaks in form?
selectnum => $threshold, # for auto-type generation
smartness => 0 | 1 | 2, # tweak "intelligence"
static => 0 | 1 | 2, # show non-editable form?
styleclass => $string, # style class to use ("fb")
stylesheet => 0 | 1 | $path, # turn on style class=
table => 0 | 1 | \%attr, # wrap form in <table>?
td => \%attr, # <td> options
tr => \%attr, # <tr> options
# These are deprecated and you should use field() instead
fieldtype => 'type',
fieldattr => \%attr,
labels => \%hash,
options => \%hash,
sortopts => 'NAME' | 'NUM' | 1 | \&sub,
# External source file (see CGI::FormBuilder::Source::File)
source => $file,
);
# Tweak fields individually
$form->field(
# Important options
name => $name, # name of field (required)
label => $string, # shown in front of <input>
type => $type, # normally auto-determined
multiple => 0 | 1, # allow multiple values?
options => \@options | \%options, # radio/select/checkbox
value => $value | \@values, # default value
# Lesser-used options
fieldset => $string, # put field into <fieldset>
force => 0 | 1, # override CGI value?
growable => 0 | 1 | $limit, # expand text/file inputs?
jsclick => $jscode, # instead of onclick
jsmessage => $string, # on JS validation failure
message => $string, # other validation failure
other => 0 | 1, # create "Other:" input?
required => 0 | 1, # must fill field in?
validate => '/regex/', # validate user input
# HTML formatting options
cleanopts => 0 | 1, # HTML-escape options?
columns => 0 | $width, # wrap field options at $width
comment => $string, # printed after field
disabled => 0 | 1, # display as grayed-out?
labels => \%hash, # deprecated (use "options")
linebreaks => 0 | 1, # insert breaks in options?
nameopts => 0 | 1, # auto-name options?
sortopts => 'NAME' | 'NUM' | 1 | \&sub, # sort options?
# Change size, maxlength, or any other HTML attr
$htmlattr => $htmlval,
);
# Check for submission
if ($form->submitted && $form->validate) {
# Get single value
my $value = $form->field('name');
# Get list of fields
my @field = $form->field;
# Get hashref of key/value pairs
my $field = $form->field;
my $value = $field->{name};
}
# Print form
print $form->render(any_opt_from_new => $some_value);
That's it. Keep reading. π
π Walkthrough π
Let's walk through a whole example to see how FormBuilder works. We'll start with this, which is actually a complete (albeit simple) form application:
use CGI::FormBuilder;
my @fields = qw(name email password confirm_password zipcode);
my $form = CGI::FormBuilder->new(
fields => \@fields,
header => 1
);
print $form->render;
The above code will render an entire form, and take care of maintaining state across submissions. But it doesn't really do anything useful at this point.
So to start, let's add the validate option to make sure the data entered is valid:
my $form = CGI::FormBuilder->new(
fields => \@fields,
header => 1,
validate => {
name => 'NAME',
email => 'EMAIL'
}
);
We now get a whole bunch of JavaScript validation code, and the appropriate hooks are added so that the form is validated by the browser onsubmit as well.
Now, we also want to validate our form on the server side, since the user may not be running JavaScript. All we do is add the statement:
$form->validate;
Which will go through the form, checking each field 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 only update our database if everything looks good:
if ($form->validate) {
# print confirmation screen
print $form->confirm;
} else {
# print the form for them to fill out
print $form->render;
}
But likeβ¦ bestie, hold up π we only wanna do this after our form has actually been submitted, because otherwise you get a form that's screaming errors at someone who hasn't even had a chance to type anything yet. Rude! So we gate it on submitted() first:
if ($form->submitted && $form->validate) {
# print confirmation screen
print $form->confirm;
} else {
# print the form for them to fill out
print $form->render;
}
Okay so now we know the form's been submitted AND it's valid β time to actually grab our values π
that's what field() is for, and you just pass it the name of the field you want:
my $email = $form->field(name => 'email');
And if the name is the only option you're passing, you can just skip the key entirely:
my $email = $form->field('email'); # same thing
Now here's the shortcut that lives in my head rent-free β¨ call field() with no arguments and you get every field back as a hashref of field/value pairs:
my $fields = $form->field; # all fields as hashref
To make life easy we'll use that form, so we can just yeet it straight into whatever sub we want:
if ($form->submitted && $form->validate) {
# form was good, let's update database
my $fields = $form->field;
# update database (you write this part)
do_data_update($fields);
# print confirmation screen
print $form->confirm;
}
Finally β say we're obsessed with our fields but we need the HTML laid out very precisely. No problem! π We just make an HTML::Template compatible template and tell FormBuilder to use it. Then in our template we drop in a couple of special tags that FormBuilder automatically expands for us:
<html>
<head>
<title><tmpl_var form-title></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 literally all we have to do is add the template option, and the rest of the code stays exactly the same:
my $form = CGI::FormBuilder->new(
fields => \@fields,
header => 1,
validate => {
name => 'NAME',
email => 'EMAIL'
},
template => 'userinfo.tmpl'
);
So our complete code so far looks like this π:
use CGI::FormBuilder;
my @fields = qw(name email password confirm_password zipcode);
my $form = CGI::FormBuilder->new(
fields => \@fields,
header => 1,
validate => {
name => 'NAME',
email => 'EMAIL'
},
template => 'userinfo.tmpl',
);
if ($form->submitted && $form->validate) {
# form was good, let's update database
my $fields = $form->field;
# update database (you write this part)
do_data_update($fields);
# print confirmation screen
print $form->confirm;
} else {
# print the form for them to fill out
print $form->render;
}
And here's the plot twist that genuinely surprised me π for a lot of applications, the above is probably all you'll ever need. Just fill in the parts that do the actual thing you care about (like the database code), and you're on your way. Slay.
Note: If you're confused at all by the backslashes you see in front of some data pieces above, like \@fields, skip down to the brief section entitled "REFERENCES" at the bottom of this document (it's short).
β¨ METHODS β¨
Okay so this documentation is very extensive, but ngl it can be a bit dizzying because there are an enormous number of options that let you tweak just about anything. So like, do yourself a favour and go stop by:
www.formbuilder.org
And click on "Tutorials" and "Examples". Then come back and use the following section as a reference later on. π«Ά
πΈ new() πΈ
This method creates a new $form object, which you then use to generate and process your form. In the very shortest version you can just hand it a list of fields for your form:
my $form = CGI::FormBuilder->new(
fields => [qw(first_name birthday favorite_car)]
);
As of 3.02:
my $form = CGI::FormBuilder->new(
source => 'myform.conf' # form and field options
);
For details on the external file format, see CGI::FormBuilder::Source::File.
Any of the options below β besides being passed to new() β can also be manipulated directly with a method of the same name. For example, to change the header and stylesheet options, either of these works:
# Way 1
my $form = CGI::FormBuilder->new(
fields => \@fields,
header => 1,
stylesheet => '/path/to/style.css',
);
# Way 2
my $form = CGI::FormBuilder->new(
fields => \@fields
);
$form->header(1);
$form->stylesheet('/path/to/style.css');
The second form is giving main character energy when you wanna wrap certain options in conditionals:
if ($have_template) {
$form->header(0);
$form->template('template.tmpl');
} else {
$form->header(1);
$form->stylesheet('/path/to/style.css');
}
The following is a description of each option, in alphabetical order π«‘:
action => $scriptβ What script to point the form to. Defaults to itself, which is the recommended setting.body => \%attrβ This takes a hashref of attributes that will be stuck in the<body>tag verbatim (for example,bgcolor,alink, etc). See thefieldattrtag for more details, and also thetemplateoption.charsetβ This forcibly overrides the charset. Better handled by loading an appropriatemessagesmodule, which will set this for you. SeeCGI::FormBuilder::Messagesfor more details.debug => 0 | 1 | 2 | 3β If set to1, the module spits copious debugging info toSTDERR. If set to2, it spits out even more gunk.3is too much. Defaults to0.fields => \@array | \%hashβ As shown above, thefieldsoption takes an arrayref of fields to use in the form. The fields will be printed out in the same order they are specified. This option is needed if you expect your form to have any fields, and is the central option to FormBuilder.
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 to fields is not very useful.
fieldtype => 'type'β This can be used to set the default type for all fields in the form. You can then override it on a per-field basis using thefield()method.fieldattr => \%attrβ This option allows you to specify any HTML attribute and have it be the default for all fields. This used to be good for stylesheets, but now that there is astylesheetoption, this is fairly useless.fieldsets => \@attrβ This allows you to define fieldsets for your form. Fieldsets are used to group fields together. Fields are rendered in order, inside the fieldset they belong to. If a field does not have a fieldset, it is appended to the end of the form.
To use fieldsets, specify an arrayref of <fieldset> names:
fieldsets => [qw(account preferences contacts)]
You can get a different <legend> tag if you specify a nested arrayref:
fieldsets => [
[ account => 'Account Information' ],
[ preferences => 'Website Preferences' ],
[ contacts => 'Email and Phone Numbers' ],
]
If you're using the source file, that looks like this:
fieldsets: account=Account Information,preferences=...
Then, for each field, specify which fieldset it belongs to:
$form->field(name => 'first_name', fieldset => 'account');
$form->field(name => 'last_name', fieldset => 'account');
$form->field(name => 'email_me', fieldset => 'preferences');
$form->field(name => 'home_phone', fieldset => 'contacts');
$form->field(name => 'work_phone', fieldset => 'contacts');
You can also automatically create a new fieldset on the fly by specifying a new one:
$form->field(name => 'remember_me', fieldset => 'advanced');
To set the <legend> in this case, you've got two options. First, you can just choose a more readable fieldset name:
$form->field(name => 'remember_me',
fieldset => 'Advanced');
Or, you can change the name using the fieldset accessor:
$form->fieldset(advanced => 'Advanced Options');
Note that fieldsets without fields are silently ignored, so you can also just specify a huge list of possible fieldsets to new(), and then only add fields as you need them. Iconic, honestly.
fieldsubs => 0 | 1β This allows autoloading of field names so you can directly access them as:
$form->$fieldname(opt => 'val');
Instead of:
$form->field(name => $fieldname, opt => 'val');
Warning: If present, it will hide any attributes of the same name. For example, if you define a name field, you won't be able to change your form's name dynamically. Also, you cannot use this format to create new fields. Use with caution. π
font => $font | \%attrβ the font face for your whole form, bestie π It's printed as a stack of<font>tags for old-browser compatibility, and it properly nests them inside every single table element. And if you pass a hashref instead of a plain font name? Then each key/value pair just becomes part of that<font>tag:
font => {face => 'verdana', size => '-1', color => 'gray'}
and that gorgeous thing becomes:
<font face="verdana" size="-1" color="gray">
ngl the docs themselves admit they used to use this all the time, but the stylesheet option is SO MUCH BETTER. Trust them: take a day, learn the basics of CSS, it's totally worth it π
header => 0 | 1β set it to 1 and a validContent-typeheader gets printed out, along with a whole bunch of HTML<body>code, a<title>tag, and so on and so on. It defaults to0, because honestly people usually end up using templates or embedding forms in other HTML πΈjavascript => 0 | 1β set to 1 and JavaScript gets generated on top of the HTML. That's the default setting already, so β¨jserror => 'function_name'β if you specify this, it gets called instead of the standard JSalert()function on error π₯ The function signature is:
function_name(form, invalid, alertstr, invalid_fields)
The function can be named literally anything you like. A simple one might look like this:
my $form = CGI::FormBuilder->new(
jserror => 'field_errors',
jshead => <<'EOJS',
function field_errors(form, invalid, alertstr, invalid_fields) {
// first reset all fields
for (var i=0; i < form.elements.length; i++) {
form.elements[i].className = 'normal_field';
}
// now attach a special style class to highlight the field
for (var i=0; i < invalid_fields.length; i++) {
form.elements[invalid_fields[i]].className = 'invalid_field';
}
alert(alertstr);
return false;
}
EOJS
);
Heads up bestie π it should return false to prevent form submission.
This one plays nice with jsfunc, which can add extra manual validations before jserror even gets called π
jsfunc => $jscodeβ this is verbatim JavaScript that gets dropped into thevalidateJavaScript function. Iconic for adding your own validation code while still keeping all the automatic hooks π¦ If something fails, you should do two things:- append to the JavaScript string
alertstr - increment the JavaScript number
invalid
- append to the JavaScript string
For example:
my $jsfunc = <<'EOJS'; # note single quote (see Hint)
if (form.password.value == 'password') {
alertstr += "Moron, you can't use 'password' for your password!\\n";
invalid++;
}
EOJS
my $form = CGI::FormBuilder->new(... jsfunc => $jsfunc);
Then this code gets automatically called whenever form validation is invoked. The docs say this option can be incredibly useful β most often it's used to bypass validation on certain submit modes. The submit button that was clicked is form._submit.value:
my $jsfunc = <<'EOJS'; # note single quotes (see Hint)
if (form._submit.value == 'Delete') {
if (confirm("Really DELETE this entry?")) return true;
return false;
} else if (form._submit.value == 'Cancel') {
// skip validation since we're cancelling
return true;
}
EOJS
Hint: to prevent accidental expansion of embedding strings and escapes, you should put your HERE string in single quotes, as shown above π
jshead => $jscodeβ if you're using JavaScript, you can also specify some JavaScript code that gets included verbatim in the<head>section of the document. The docs are like "I'm not very fond of this one, what you probably want is the previous option" π so yeah,jsfuncis right there.keepextras => 0 | 1 | \@arrayβ set it to 1 and any extra parameters that aren't in your fields declaration get kept as hidden fields in the form β¨ But plot twist: you need to usecgi_param(), NOTfield(), to actually access those values.
Super useful if you want to keep some extra parameters like mode or company hanging around without them being valid form fields:
keepextras => 1
That preserves any extra params. You can also hand it an arrayref, and then only the params in that list get preserved π For example:
keepextras => [qw(mode company)]
will only preserve the params mode and company. Again, to access them:
my $mode = $form->cgi_param('mode');
$form->cgi_param(name => 'mode', value => 'relogin');
See "CGI.pm" for the details on param() usage π
labels => \%hashβ likevalues, this is a list of key/value pairs where the keys are the names of thefieldsyou specified above. By default FormBuilder does some snazzy case and character conversion to build pretty labels for you πΈ But if you want to explicitly name your fields, this is the 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 even contemplating this option, what you actually want is a template π
lalign => 'left' | 'right' | 'center'β a legacy shortcut for:
th => { align => 'left' }
Even better: use the stylesheet option and tweak the .fb_label class. Either way β don't use this π
langβ this forcibly overrides the lang. Honestly it's better handled by loading an appropriatemessagesmodule, which will set this for you β¨ See CGI::FormBuilder::Messages for the full details.method => 'post' | 'get'β the type of CGI method to use, eitherpostorget. Defaults togetif nothing is specified. But lowkey important: for forms that cause changes on the server β database inserts, that whole vibe β you should use thepostmethod πmessages => 'auto' | $file | \%hash | $localeβ this option overrides the default FormBuilder messages so you can get multilingual locale support (or just different text for the picky ones π). For all the deets on this option, please refer to CGI::FormBuilder::Messages.name => $stringβ this names the form. It's optional, but when you use it, it renames several key variables and functions according to the name of the form π¦ On top of that, it also adds the following<div>tags to each row of the table:
<tr id="${form}_${field}_row">
<td id="${form}_${field}_label">Label</td>
<td id="${form}_${field}_input"><input tag></td>
<td id="${form}_${field}_error">Error</td><!-- if invalid -->
</tr>
These changes let you (a) use multiple forms in a sequential application and/or (b) display multiple forms inline in one single document π So if you're building a complex multi-form app and things are going wrong, try naming your forms. Main character energy for your <form> tags, fr fr.
options => \%hashβ this is one of several meta-options that lets you specify stuff for multiple fields at once π
my $form = CGI::FormBuilder->new(
fields => [qw(part_number department in_stock)],
options => {
department => [qw(hardware software)],
in_stock => [qw(yes no)],
}
);
This has the exact same effect as using field() for the department and in_stock fields to set options individually π
params => $objectβ this specifies an object from which the parameters should be derived. The object must have aparam()method that returns values for each parameter by name. By default a CGI object is automatically created and used for you β¨
But you'll 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 you're using a post form method:
use CGI;
use CGI::FormBuilder;
my $q = new CGI;
my $form = CGI::FormBuilder->new(... params => $q);
Usually you don't need to do this β only if you need to access other parameters outside of FormBuilder's control π
required => \@array | 'ALL' | 'NONE'β this is the list of values that are required to be filled in. Any fields named here must be filled in by the user π If therequiredoption isn't specified, then by default any fields named invalidateare required.
On top of that, required also takes two other settings, the strings ALL and NONE. Specify ALL and every field is required. Specify NONE and none of them are, in spite of whatever may be set via the validate option π
This is useful when you have fields that are optional but that you still want validated if they get filled in:
my $form = CGI::FormBuilder->new(
fields => qw[/name email/],
validate => { email => 'EMAIL' },
required => 'NONE'
);
That makes the email field optional β but if it's filled in, it has to match the EMAIL pattern β¨
Also, super important to note: if both the required and validate options are specified, then they're taken as an intersection. That is, only those fields specified as required 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)]
);
That makes the name field mandatory, but the email field optional π¦ However β if email is filled in, then it must match the builtin EMAIL pattern. Periodt.
reset => 0 | 1 | $stringβ set it to 0 and theResetbutton isn't printed at all. Set it to text and that text gets printed out as the reset button. Defaults to printing out a button that saysResetπselectnumβ this is the lil dial that controls FormBuilder's auto-type generation π here's the tea: if a field hasoptions, it defaults to a radio group. But if there are more thanselectnumoptions, it becomes a select list instead. The default is 5 or more options. Like so:
# 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);
# Single items are checkboxes (allows unselect)
$form->field(name => 'answer', options => ['Yes']);
There's no threshold for checkboxes, because β think about it β they're literally a multi-radio select group π
so a radio group becomes a checkbox group if the multiple option is specified and the field has fewer than selectnum options. Got it? π«Ά
smartnessβ0 | 1 | 2. By default CGI::FormBuilder tries to be pretty smart for you, like figuring out field types based on their names and how many options there are β¨ if you don't want any of that behavior at all, setsmartnessto0. If you want it to be really smart β like figuring out which validation routines to use for you β set it to2. It defaults to1.sortoptsβBUILTIN | 1 | \&sub. If you specify this tonew(), it does the exact same thing as the same-named option tofield(), only it applies to all the fields. One dial, every field. slay πsourceβ$filename. You can use this option to initialize FormBuilder from an external configuration file π¦ this lets you separate your field code from your form layout, which is pretty cool. See CGI::FormBuilder::Source::File for details on the format of the external file.staticβ0 | 1 | 2. If set to1, the form gets output with static hidden fields. If set to2, then on top of that, fields without values are omitted. Defaults to0.stickyβ0 | 1. Determines whether form values should be sticky across submissions. Defaults to1, meaning values are sticky. But you might wanna set it to0if you have a form that does something like adding parts to a database π see the "EXAMPLES" section for a good example.submitβ0 | 1 | $string | \@array. If set to0, the "Submit" button isn't printed at all. By default it creates a button that says "Submit" verbatim. If you give it an argument, 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 creates multiple submit buttons, each with a different value β¨ and on top of that, when it's submitted only the one that was clicked gets 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 either one submits the form, but you'd be able to see which one was submitted via the submitted() function:
my $clicked = $form->submitted;
So if the user clicked "Add A Gift", that's what ends up in the $clicked variable above. This gives you 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 πΈ
styleclassβ$string. The string to use as the "style" name, if the following option is enabled.stylesheetβ0 | 1 | $path. This option turns on stylesheets in the HTML output by FormBuilder π each element is printed with theclassofstyleclass(fbby default). It's up to you to provide the actual style definitions, bestie β no cap. If you provide a$pathrather than just a 1/0 toggle, then that$pathwill be included in a<link>tag as well.
The following tags are created by this option:
${styleclass} top-level table/form class
${styleclass}_required labels for fields that are required
${styleclass}_invalid any fields that failed validate()
If you're contemplating stylesheets, the best thing is to just turn this option on, then see what's spit out π see the section on "STYLESHEETS" for more details on FormBuilder style sheets.
tableβ0 | 1 | \%tabletags. By default FormBuilder decides how to lay out the form based on the number of fields, values, etc. You can force it into a table by specifying1, or force it out of one with0.
If you specify a hashref instead, then those get used to create the <table> tag. For example, to create a table with no cellpadding or cellspacing, use:
table => {cellpadding => 0, cellspacing => 0}
Also, you can specify options to the <td> and <tr> elements as well, same fashion π
templateβ$filename | \%hash | \&sub | $object. This points to a filename containing anHTML::Template-compatible template to use for laying out the HTML π¦ you can also specify thetemplateoption as a reference to a hash, which lets you further customize the template processing options, or use other template engines.
If template points to a sub reference, that routine gets called and its return value directly returned. If it's an object, then that object's render() routine is called and its value returned.
For lots more information, please see CGI::FormBuilder::Template.
textβ$text. This is text that's included below the title but above the actual form β¨ useful if you wanna say something simple like "Contact $adm for more help", but if you want lots of text, check out thetemplateoption above instead.titleβ$title. Takes a string to use as the title of the form. iconic, honestly πvaluesβ\%hash | \@array. Thevaluesoption takes a hashref of key/value pairs specifying the default values for the fields π these values get overridden by the values entered by the user across the CGI. The values are used case-insensitively, which makes 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 the user can change them if they want. For example:
my $rec = $sth->fetchrow_hashref;
my $form = CGI::FormBuilder->new(fields => \@fields,
values => $rec);
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 | $object. This option takes either a hashref of key/value pairs or a Data::FormValidator object.
In the case of the hashref, each key is the name of a field from the fields option, or the string "ALL" β in which case it applies to all fields π«Ά each value is one of the following:
- a regular expression in 'quotes' to match against
- an arrayref of values, of which the field must be one
- a string that corresponds to one of the builtin patterns
- a string containing a literal code comparison to do
- a reference to a sub to be used to validate the field
(the sub will receive the value to check as the first arg)
In addition, 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 toggles each field to make it required. However, you can use the required option to change this β see it for more details π
Let's look at a concrete example. Note that the javascript validation is a negative match, while the perl validation is a positive match.
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 => \&check_password,
confirm_password => {
javascript => '!= form.password.value', # neg
perl => 'eq $form->field("password")', # pos
},
},
);
# simple sub example to check the password
sub check_password ($) {
my $v = shift; # first arg is value
return unless $v =~ /^.{6,8}/; # 6-8 chars
return if $v eq "password"; # dummy check
return unless passes_crack($v); # you write "passes_crack()"
return 1; # success
}
This would create both JavaScript and Perl routines 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
- "password" passes the checks done by check_password(), meaning
that the sub returns true
- "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 in both JavaScript and Perl code π as such, specifying a qr// will NOT work.
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 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β literally any non-null value. yes queen, anything goes πWORDβ a word, and by "word" we mean\w+NAMEβ matches[a-zA-Z]only, letters bestie, that's itFNAMEβ a person's first name, like"Jim"or"Joe-Bob"LNAMEβ a last name, like"Smith"or"King, Jr."NUMβ a number, decimal or integerINTβ integerFLOATβ floating-point numberPHONEβ phone number shaped like"123-456-7890"or"(123) 456-7890"INTPHONEβ international phone number, shaped like"+prefix local-number"EMAILβ email addr shaped like"name@host.domain"CARDβ credit card, Amex included, with or without the-'sDATEβ date inMM/DD/YYYYformatEUDATEβ date inDD/MM/YYYYformatMMYYβ date inMM/YYorMMYYformatMMYYYYβ date inMM/YYYYorMMYYYYformatCCMMβ strict checking for a valid credit card 2-digit month,([0-9]|1[012])CCYYβ valid credit card 2-digit yearZIPCODEβ US postal code in12345or12345-6789formatSTATEβ valid two-letter state, all uppercaseIPV4β valid IPv4 addressNETMASKβ valid IPv4 netmaskFILEβ UNIX format filename, like/usr/binWINFILEβ Windows format filename, likeC:\windows\systemMACFILEβ MacOS format filename, likefolder:subfolder:subfolderHOSTβ valid hostname, likesome-nameDOMAINβ valid domainname, likewww.i-love-bacon.comETHERβ valid ethernet address, using either:or.as separators
okay so bestie, I know some of the above are US-centric π but like, that's where the author lives, so. :-) If you need different processing, just roll your own regular expression and pass it in β you're literally a genius, you got this. And if there's something really useful, let them know and maybe they'll add it π«Ά
You can also pass a Data::FormValidator object as the value of "validate". This lets you do things like requiring any one of several fields (but where you don't care which one). In this case, the "required" option to new() is ignored, since you should be setting the required fields through your FormValidator profile. iykyk β¨
By default, FormBuilder will try to use a profile named fb to validate itself. You can change this by providing a different profile name when you call validate().
heads up babe: note that currently, doing validation through a FormValidator object doesn't generate any JavaScript validation code for you. no free JS, sorry π
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.
prepare()
This function prepares a form for rendering. It's automatically called by render(), but calling it yourself may be useful if you're using Catalyst or some other large framework. It returns the same hash that will be used by render():
my %expanded = $form->prepare;
You could use this to, say, tweak some custom values and then pass it to your own rendering object. main character energy honestly π
render()
This function renders the form into HTML, and returns a string containing the form. The most common use is simply:
print $form->render;
You can also supply options to render(), just like you had called the accessor functions individually. These two uses are equivalent:
# this code:
$form->header(1);
$form->stylesheet('style.css');
print $form->render;
# is the same as:
print $form->render(header => 1,
stylesheet => 'style.css');
important!! note that both forms make permanent changes to the underlying object. So the next call torender()will still have theheaderandstylesheetoptions in either case. it's giving "sticky settings" fr fr π
field()
This method is used to both get at field values:
my $bday = $form->field('birthday');
As well as make changes to their attributes:
$form->field(name => 'fname',
label => "First Name");
A very common use is to specify a list of options and/or the field type:
$form->field(name => 'state',
type => 'select',
options => \@states); # you supply @states
In addition, when you call field() without any arguments, it returns a list of valid field names in an array context:
my @fields = $form->field;
And a hashref of field/value pairs in scalar context:
my $fields = $form->field;
my $name = $fields->{name};
lowkey important caveat: note that if you call it in this manner, you only get one single value per field. This is fine as long as you don't have multiple values per field (the normal case). But π if you have a field that allows multiple options:
$form->field(name => 'color', options => \@colors,
multiple => 1); # allow multi-select
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 "name" option is described first, and the remaining options are in order. slay, let's go π
name => $nameβ the field to manipulate. The"name =>"part is optional if it's the only 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');
add_after_option => $htmlβ adds the specified HTML code after each checkbox (or radio) option.add_before_option => $htmlβ adds the specified HTML code before each checkbox (or radio) option. the before/after duo, iconic π¦columns => 0 | $widthβ if set and the field is of type'checkbox'or'radio', then the options will be wrapped at the given width.comment => $stringβ this prints out the given comment after the field. A good use of this is for additional help on what the field should contain:
$form->field(name => 'dob',
label => 'D.O.B.',
comment => 'in the format MM/DD/YY');
The above would yield something like this:
D.O.B. [____________] in the format MM/DD/YY
The comment is rendered verbatim, meaning you can use HTML links or code in it if you want. go off β¨
cleanopts => 0 | 1β if set to 1 (the default), field options are escaped to make sure any special chars don't screw up the HTML. Set to 0 if you want to include verbatim HTML in your options, and know what you're doing. (and like... actually know, bestie π)cookies => 0 | 1β controls whether to generate a cookie if"sessionid"has been set. This also requires that"header"be set as well, since the cookie is wrapped in the header. Defaults to 1, meaning it will automatically work if you turn on"header". πforce => 0 | 1β this is used in conjunction with the"value"option to forcibly override a field's value. See below under the"value"option for more details. For compatibility with"CGI.pm", you can also call this option"override"instead, but don't tell anyone π€«growable => 0 | 1 | $limitβ this option adds a button and the appropriate JavaScript code to your form to allow the additional copies of the field to be added by the client filling out the form. Currently, this only works with"text"and"file"field types.
If you set "growable" to a positive integer greater than 1, that will become the limit of growth for that field. You won't be able to add more than $limit extra inputs to the form, and FormBuilder will issue a warning if the CGI params come in with more than the allowed number of values. respect the limit fr fr π
jsclick => $jscodeβ this is a cool abstraction over directly specifying the JavaScript action. This turns out to be extremely useful, since if a field type changes from"select"to"radio"or"checkbox", then the action changes from"onchange"to"onclick". Why?!?! π (no seriously, why)
So if you said:
$form->field(name => 'credit_card',
options => \@cards,
jsclick => 'recalc_total();');
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. iykyk π₯
jsmessage => $stringβ you can use this to specify your own custom message for the field, which will be printed if it fails validation. The"jsmessage"option affects the JavaScript popup box, and the"message"option affects what is printed out if the server-side validation fails. If"message"is specified but not"jsmessage", then"message"will be used for JavaScript as well.
$form->field(name => 'cc',
label => 'Credit Card',
message => 'Invalid credit card number',
jsmessage => 'The card number in "%s" is invalid');
The %s will be filled in with the field's "label". cute little placeholder moment π
label => $stringβ this is the label printed out before the field. By default it is automatically generated from the field name. If you want to be really lazy, get in the habit of naming your database fields as complete words so you can pass them directly to/from your form. future-you will thank you πlabels => \%hashβ this option tofield()is outdated. You can get the same effect by passing data structures directly to the"options"argument (see below). If you have well-named data, check out the"nameopts"option.
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:
$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. As mentioned, this has the exact same effect:
$form->field(name => 'state',
options => [
[ AZ => 'Arizona' ],
[ CA => 'California' ],
[ NV => 'Nevada' ],
[ OR => 'Oregon' ],
[ WA => 'Washington ],
]);
(note: that missing closing quote in 'Washington is straight from the original, bestie β not me being chaotic πΈ)
Like, honestly? I can think of a few rare situations where you'd have a whole set of predefined labels but only some of them show up in a given field... but bestie, usually you should just use the options arg, fr fr. π
linebreaks => 0 | 1β kinda like the top-levellinebreaksoption, but this one drops breaks between your options so everything's more spaced out. Super useful with radio buttons and checkboxes especially β it's giving breathing room β¨message => $stringβ just likejsmessage, this customizes the output error string whenever server-side validation fails for the field. Oh and heads up: themessageoption also gets used for JavaScript messages if you set it but don't setjsmessage. The details live above underjsmessageπ«Άmultiple => 0 | 1β set this to 1 and the user can pick multiple values from the options you provided. It turns radio groups into checkboxes and selects into multi-selects. Defaults to being automatically figured out based on the number of values πnameopts => 0 | 1β set it to 1 and your select list options get automatically named using the exact same algorithm as field labels. Like so:
$form->field(name => 'department',
options => qw[(molecular_biology
philosophy psychology
particle_physics
social_anthropology)],
nameopts => 1);
Which 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 determined in the same way as the names for the fields β iconic. It's designed as a simpler alternative to using custom options data structures, for when your data is regular enough to support it πΈ
other => 0 | 1 | \%attrβ if set, this automatically creates an "other" field to the right of the main field. So useful if you want to present a preset list but also let the user enter their own entry:
$form->field(name => 'vote_for_president',
options => [qw(Bush Kerry)],
other => 1);
That would generate HTML somewhat like this:
Vote For President: [ ] Bush [ ] Kerry [ ] Other: [______]
If the "other" button gets checked, the box becomes editable so the user can write in their own text. And this "other" box is subject to the same validation as the main field, so your data for that field stays consistent π
options => \@options | \%options | \&subβ this takes an arrayref of options. It also automatically results in the field becoming a radio (if < 5) or select list (if >= 5), unless you explicitly set the type with thetypeparameter:
$form->field(name => 'opinion',
options => [qw(yes no maybe so)]);
From that, you'll 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>
Also! It can accept more complicated data structures, so you can specify different labels and values for your options. If a given item is either an arrayref or a hashref, then the first element is taken as the value and the second as the label. For example, 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);
Finally, you can specify a \&sub which must return either an \@arrayref or \%hashref of data, which is then expanded using the same algorithm π¦
optgroups => 0 | 1 | \%hashrefβ ifoptgroupsis specified for a field (selectfields only), then theoptionsarray above gets parsed so that the third argument is taken as the name of the optgroup, and an<optgroup>tag is generated appropriately β¨
An example makes this behavior immediately obvious:
my $opts = $dbh->selectall_arrayref(
"select id, name, category from software
order by category, name"
);
$form->field(name => 'software_title',
options => $opts,
optgroups => 1);
The optgroups setting would then parse the third element of $opts so that you'd get an optgroup every time that category changed:
<optgroup label="antivirus">
<option value="12">Norton Anti-virus 1.2</option>
<option value="11">McAfee 1.1</option>
</optgroup>
<optgroup label="office">
<option value="3">Microsoft Word</option>
<option value="4">Open Office</option>
<option value="6">WordPerfect</option>
</optgroup>
In addition, if optgroups is instead a hashref, then the name of the optgroup is gotten from that. Using the example above, this would help if you had the category name in a separate table and were just storing the category_id in the software table. You could provide an optgroups hash like:
my %optgroups = (
1 => 'antivirus',
2 => 'office',
3 => 'misc',
);
$form->field(..., optgroups => \%optgroups);
Note: FormBuilder makes no attempt to properly sort your option optgroups β it is up to you to provide them in a sensible order. π
required => 0 | 1β set to 1 and the field must be filled in:
$form->field(name => 'email', required => 1);
Honestly this is rarely useful β what you probably want are the validate and required options to new(). iykyk π
selectname => 0 | 1 | $stringβ by default this is set to 1, and any single-select lists get prefixed by the messageform_select_default(-select-for English). Set it to 0 and that string isn't prefixed. Set it to a$stringand that string is used explicitly.
Philosophically, the -select- behavior is intentional because it allows a null item to be transmitted (same as not checking any checkboxes or radio buttons). Otherwise, the first item in a select list is automatically sent when the form is submitted. If you'd like an item to be "pre-selected", consider using the value option to specify the default value π
sortopts => BUILTIN | 1 | \&subβ if set, and there are options, then the options get sorted in the specified order. There are four possible values for theBUILTINsetting:
NAME Sort option values by name
NUM Sort option values numerically
LABELNAME Sort option labels by name
LABELNUM Sort option labels numerically
For example:
$form->field(name => 'category',
options => \@cats,
sortopts => 'NAME');
Would sort the @cats options in alphabetic (NAME) order. The option NUM would sort them in numeric order. If you specify 1, then an alphabetic sort is done, just like the default Perl sort π
In addition, you can specify a sub reference which takes pairs of values to compare and returns the appropriate return value that Perl sort() expects.
type => $typeβ the type of input box to create. Default istext, and valid values include anything allowed by the HTML specs, includingselect,radio,checkbox,textarea,password,hidden, and so on π
By default, the type is automatically determined by FormBuilder based on the following algorithm:
Field options?
No = text (done)
Yes:
Less than 'selectnum' setting?
No = select (done)
Yes:
Is the 'multiple' option set?
Yes = checkbox (done)
No:
Have just one single option?
Yes = checkbox (done)
No = radio (done)
I recommend you let FormBuilder do this for you in most cases, and only tweak the ones you really need to π₯
value => $value | \@valuesβ thevalueoption 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 radio group, depending on the number of options specified.
If a CGI value is present, it will always win. To forcibly change a value, you need to specify the force option:
# Example that hides credit card on confirm screen
if ($form->submitted && $form->validate) {
my $val = $form->field;
# hide CC number
$form->field(name => 'credit_card',
value => '(not shown)',
force => 1);
print $form->confirm;
}
This would print out the string (not shown) on the confirm() screen instead of the actual number π
validate => '/regex/'β similar to thevalidateoption used innew(), this affects the validation of just that single field. As such, rather than a hashref, you'd 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? It needs to be usable by the JavaScript routines as well. π
$htmlattr => $htmlval
okay so on top of all the tags we already covered, field() is lowkey flexible like that β it'll take literally any other valid HTML attribute and drop it into the tag verbatim. no gatekeeping, no filtering, just vibes. π«Ά
say you wanted to change the class of the field (like if you're doing the stylesheet + template thing), you'd go:
$form->field(name => 'email', class => 'FormField',
size => 80);
then when you call $form->render you'd get back a field something like:
<input type="text" name="email" class="FormField" size="80">
(and yeah bestie, for that to really work you still gotta create a class called "FormField" in your stylesheet β the attribute is not gonna style itself π
)
also peep the "fieldattr" option, which provides global attributes to all fields. iconic.
cgi_param()
so the field() method up there? it only ever returns fields you explicitly defined in your form. excess parameters get silently ignored, to help ensure users can't mess with your form. honestly a slay for security. π‘οΈ
but sometimes you do want extra params so you can maintain state β you just don't want them appearing in your form. branding is the easy example:
http://hr-outsourcing.com/newuser.cgi?company=mr_propane
this could change your page's HTML so it displays the appropriate company name and logo, without polluting your form parameters. main character branding moment, fr.
this call simply redispatches to CGI.pm's param() method, so go consult those docs for more tea. π΅
tmpl_param()
this one lets you manipulate template parameters directly. extending the example above:
my $form = CGI::FormBuilder->new(template => 'some.tmpl');
my $company = $form->cgi_param('company');
$form->tmpl_param(company => $company);
then, in your template:
Hello, <tmpl_var company> employee!
<p>
Please fill out this form:
<tmpl_var form-start>
<!-- etc... -->
for really precise template control, you can actually create your own template object and then pass it directly to FormBuilder. see CGI::FormBuilder::Template for the deets. π
sessionid()
gets and sets the sessionid, which is stored in the special form field _sessionid. by default no session ids are generated or used β it's just a hook. rather, this is intended to provide a hook for you to easily integrate this with a session id module like CGI::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 get the value "0123-091231" in your script. conversely, if you generate a new sessionid on your own and wish to include it automatically, simply set it as follows:
$form->sessionid($id);
if the sessionid is set, and "header" is set, then FormBuilder will also automatically generate a cookie for you. πͺ
see "EXAMPLES" for the CGI::Session example.
submitted()
this returns the value of the "Submit" button if the form has been submitted, undef otherwise. so you can either test it in a boolean context:
if ($form->submitted) { ... }
or 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') {
...
}
best practice bestie: it's best to call validate() in conjunction with this to make sure the form validation works. and 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. super 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()
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 if you have to deal with different geos:
if ($location eq 'US') {
$form->validate(state => 'STATE', zipcode => 'ZIPCODE');
} else {
$form->validate(state => '/^\w{2,3}$/');
}
you can also provide a Data::FormValidator object as the first argument. in that case, the second argument (if present) will be interpreted as the name of the validation profile to use. a single string argument will also be interpreted as a validation profile name. πͺ
heads up π β 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 example above, but for most applications you want to pass your validation requirements in via the"validate"option to thenew()function, and just call the validate() function with no arguments. periodt.
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. it's actually just a special wrapper around render(), twiddling a couple options. β¨
if you're using templates, you probably want to specify a separate success template, such as:
if ($form->submitted && $form->validate) {
print $form->confirm(template => 'success.tmpl');
} else {
print $form->render(template => 'fillin.tmpl');
}
so that you don't get the same screen twice. no rerun energy, we don't want it. π
mailconfirm()
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. simple, cute, done.
mailresults()
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: Nate 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=Nate 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". π
mailresults() with plugin
now you can also specify a plugin to use with mailresults, in the namespace CGI::FormBuilder::Mail::*. these plugins may depend on other libraries. for example, this:
$form->mailresults(
plugin => 'FormatMultiPart',
from => 'Mark Hedges <hedges@ucsd.edu>',
to => 'Nate Wiger <nwiger@gmail.com>',
smtp => $smtp_host_or_ip,
format => 'plain',
);
will send your mail formatted nicely in text using Text::FormatTable. (and if you used format => 'html' it would use HTML::QuickTable.) π₯
this particular plugin uses MIME::Lite and Net::SMTP to communicate directly with the SMTP server, and does not rely on a shell escape. see CGI::FormBuilder::Mail::FormatMultiPart for more information.
this establishes a simple mail plugin implementation standard for your own mailresults() plugins:
- the plugin should reside under the
CGI::FormBuilder::Mail::*namespace. - it should have a constructor
new()which accepts a hash-as-array of named arg parameters, includingform => $form. - it should have a
mailresults()object method that does the right thing. - it should use
CGI::FormBuilder::Utilandpuke()if something goes wrong. π
calling $form->mailresults( plugin => 'Foo', ... ) will load CGI::FormBuilder::Mail::Foo and will pass the FormBuilder object as a named param 'form' with all other parameters passed intact.
if it should croak, confess, die or otherwise break if something goes wrong, FormBuilder.pm will warn any errors and the built-in mailresults() method will still try. resilient queen. π
mail()
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. π¦
π COMPATIBILITY π
the following methods are provided to make FormBuilder behave more like other modules, when desired. iykyk.
header()
returns a CGI.pm header, but only if header => 1 is set.
param()
this is an alias for field(), provided for compatibility. however, while field() does act "compliantly" for easy use in CGI::Session, Apache::Request, etc, it is not 100% the same. as such, i recommend you use field() in your code, and let receiving objects figure the param() thing out when needed:
my $sess = CGI::Session->new(...);
$sess->save_param($form); # will see param()
query_string()
this returns a query string similar to CGI.pm, but ONLY containing form fields and any "keepextras", if specified. other params are ignored.
self_url()
this returns a self url, similar to CGI.pm, but again ONLY with form fields.
script_name()
an alias for $form->action. π
β¨ STYLESHEETS (CSS) β¨
okay bestie, this is the glow-up section π
if you turn on the stylesheet option β literally just set it to 1, or point it at the path of a CSS file β then FormBuilder will automatically spit out style classes for every single form element. every one. no cap. π
here's the whole roster, alphabetically-adjacent and iconic:
fbβ the main form table πfb_labelβ thetdcontaining the field labelfb_fieldβ thetdcontaining the field input tagfb_submitβ thetdcontaining the submit button(s)fb_inputβ input typesfb_selectβ select typesfb_checkboxβ checkbox typesfb_radioβ radio typesfb_optionβ labels for checkbox/radio optionsfb_buttonβ button typesfb_hiddenβ hidden typesfb_staticβ static typesfb_requiredβ the span wrapped around labels for required fields βfb_invalidβ the span wrapped around labels for invalid fields πfb_commentβ the span wrapped around the field comment π«Άfb_errorβ the span wrapped around the field error message π
and here's a cute little starter fb.css you can just drop in β it spruces up a couple basic form features and honestly it ate:
/* FormBuilder */
.fb {
background: #ffc;
font-family: verdana,arial,sans-serif;
font-size: 10pt;
}
.fb_label {
text-align: right;
padding-right: 1em;
}
.fb_comment {
font-size: 8pt;
font-style: italic;
}
.fb_submit {
text-align: center;
}
.fb_required {
font-weight: bold;
}
.fb_invalid {
color: #c00;
font-weight: bold;
}
.fb_error {
color: #c00;
font-style: italic;
}
obvi, if you already know your way around CSS you already know a lot more is possible β go off, customize everything π
also: you can mess with all the id's (if you name your forms) to manipulate fields more exactly. iykyk π₯
β¨ EXAMPLES β¨
ngl, 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 is giving order form realness: it has validation for the important fields and a "Cancel" button to abort the whole thing. π
#!/usr/bin/perl
use strict;
use CGI::FormBuilder;
my @states = my_state_list(); # you write this
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [
qw(first_name last_name
email send_me_emails
address state zipcode
credit_card expiration)
],
header => 1,
title => 'Finalize Your Order',
submit => ['Place Order', 'Cancel'],
reset => 0,
validate => {
email => 'EMAIL',
zipcode => 'ZIPCODE',
credit_card => 'CARD',
expiration => 'MMYY',
},
required => 'ALL',
jsfunc => <<EOJS,
// skip js validation if they clicked "Cancel"
if (this._submit.value == 'Cancel') return true;
EOJS
);
# Provide a list of states
$form->field(name => 'state',
options => \@states,
sortopts=> 'NAME');
# Options for mailing list
$form->field(name => 'send_me_emails',
options => [[1 => 'Yes'], [0 => 'No']],
value => 0); # "No"
# Check for valid order
if ($form->submitted eq 'Cancel') {
# redirect them to the homepage
print $form->cgi->redirect('/');
exit;
}
elsif ($form->submitted && $form->validate) {
# your code goes here to do stuff...
print $form->confirm;
}
else {
# either first printing or needs correction
print $form->render;
}
This will create a form called "Finalize Your Order" that gives you a pulldown menu for the "state", a radio group for "send_me_emails", and normal text boxes for the rest. Then it validates all the fields, using specific patterns for those fields specified to "validate". Iconic behavior, fr fr. β
π Ex2: order_form.cgi π
Here's an example that adds some fields dynamically, and uses the "debug" option to spit out gook:
#!/usr/bin/perl
use strict;
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [
qw(first_name last_name email
address state zipcode)
],
header => 1,
debug => 2, # gook
required => 'NONE',
);
# This adds on the 'details' field to our form dynamically
$form->field(name => 'details',
type => 'textarea',
cols => '50',
rows => '10');
# And this adds user_name with validation
$form->field(name => 'user_name',
value => $ENV{REMOTE_USER},
validate => 'NAME');
if ($form->submitted && $form->validate) {
# ... more code goes here to do stuff ...
print $form->confirm;
} else {
print $form->render;
}
In this case, none of the fields are required, but the "user_name" field will still be validated if filled in. Lowkey efficient. β¨
π¦ Ex3: ticket_search.cgi π¦
This is a simple search script that uses a template to lay out the search parameters very precisely. Note that we set our options for our different fields and types.
#!/usr/bin/perl
use strict;
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(
fields => [qw(type string status category)],
header => 1,
template => 'ticket_search.tmpl',
submit => 'Search', # search button
reset => 0, # and no reset
);
# Need to setup some specific field options
$form->field(name => 'type',
options => [qw(ticket requestor hostname sysadmin)]);
$form->field(name => 'status',
type => 'radio',
options => [qw(incomplete recently_completed all)],
value => 'incomplete');
$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;
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.
<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. Separation of concerns ate, periodt. π
πΈ 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
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. Main character energy for form UX, honestly. π§
#!/usr/bin/perl
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 => '/^[PL]\d{2}-\d{4}-\d{4}$/',
pn => '/^[AQM]\d{2}-\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. No cap. π₯
π Ex6: Session Management π
This creates a session via "CGI::Session", and ties it in with FormBuilder:
#!/usr/bin/perl
use CGI::Session;
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(fields => \@fields);
# Initialize session
my $session = CGI::Session->new('driver:File',
$form->sessionid,
{ Directory=>'/tmp' });
if ($form->submitted && $form->validate) {
# Automatically save all parameters
$session->save_param($form);
}
# Ensure we have the right sessionid (might be new)
$form->sessionid($session->id);
print $form->render;
Yes, it's pretty much that easy. See CGI::FormBuilder::Multi for how to tie this into a multi-page form. Go off, bestie. ππ
β¨ FREQUENTLY ASKED QUESTIONS (FAQ) β¨
okay so there are a couple of questions and lowkey subtle traps that keep poking people on the reg π here are some hints, bestie π«Ά
π
I'm confused. Why doesn't this work like CGI.pm?
if you're used to CGI.pm, you gotta do a lil brain shift when you're working with this module, fr.
FormBuilder is designed to address fields as abstract entities. like, you don't create a "checkbox" or a "radio group" per se. instead, you create a field for the data you wanna collect. the HTML representation is literally just one property of that field. main character energy tbh π
so if you want a single-option checkbox, just say something like this:
$form->field(name => 'join_mailing_list',
options => ['Yes']);
if you want it checked by default, you add the value arg:
$form->field(name => 'join_mailing_list',
options => ['Yes'],
value => 'Yes');
see what's happening? you're creating a field that has one possible option: "Yes". then you're saying its current value is, in fact, "Yes". this results in FormBuilder creating a single-option field (which is a checkbox by default) and selecting the requested value (meaning the box will be checked βοΈ).
if you want multiple values, then all you gotta do is specify multiple options:
$form->field(name => 'join_mailing_list',
options => ['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 sooo much more flexibility and less code maintenance. if you wanna be able to accept multiple values, simply use the multiple arg:
$form->field(name => 'favorite_colors',
options => [qw(red green blue)],
multiple => 1);
in all of these examples, to get the data back you just use the field() method:
my @colors = $form->field('favorite_colors');
and the rest is taken care of for you. slay π
π¦ How do I make a multi-screen/multi-mode form?
this is easily doable, but you gotta remember a couple things. most importantly: FormBuilder only knows about those fields you've told it about. so let's assume you're gonna 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
keepextrasoption:
my $form = CGI::FormBuilder->new(..., keepextras => 1);
this maintains the "mode" field as a hidden field across requests automatically. iconic β¨
- second, you need to realize that since the
"mode"is not a defined field, you have to get it via thecgi_param()method:
my $mode = $form->cgi_param('mode');
this allows you to build a large multiscreen application easily, even integrating it with modules like CGI::Application if you want. no cap, that's a vibe π
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');
# Change our form based on our mode
if ($mode eq 'view') {
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [qw(...)],
);
} elsif ($mode eq 'edit') {
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [qw(...)],
);
}
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's 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');
# Change our form based on our mode
# Note: since it is post, must specify the 'params' option
if ($mode eq 'view') {
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [qw(...)],
params => $cgi # get CGI params
);
} elsif ($mode eq 'edit') {
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [qw(...)],
params => $cgi # get CGI params
);
}
or, since FormBuilder gives you a cgi_param() function, you could also modify your code so you use FormBuilder exclusively, as in the previous question. easy β¨
πΈ How can I change option XXX based on a conditional?
to change an option, simply use its accessor at any time:
my $form = CGI::FormBuilder->new(
method => 'post',
fields => [qw(name email phone)]
);
my $mode = $form->cgi_param('mode');
if ($mode eq 'add') {
$form->title('Add a new entry');
} elsif ($mode eq 'edit') {
$form->title('Edit existing entry');
# do something to select existing values
my %values = select_values();
$form->values(\%values);
}
print $form->render;
using the accessors makes permanent changes to your object, so be aware that if you wanna reset something to its original value later, you'll have to first save it and then reset it π:
my $style = $form->stylesheet;
$form->stylesheet(0); # turn off
$form->stylesheet($style); # original setting
you can also specify options to render(), although using the accessors is the preferred way. iykyk π
π How do I manually override the value of a field?
you must specify the "force" option:
$form->field(name => 'name_of_field',
value => $value,
force => 1);
if you don't specify "force", then the CGI value will always win. this is because of the stateless nature of the CGI protocol. no cap, that's just how it is π€
π§ How do I make it so that the values aren't shown in the form?
turn off sticky:
my $form = CGI::FormBuilder->new(... sticky => 0);
by turning off the "sticky" option, you'll still be able to access the values, but they won't show up in the form. sneaky sneaky π
π 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. that's literally it bestie π
π Can FormBuilder handle file uploads?
it sure can, and it's really easy too! π₯ just change the "enctype" as an option to new():
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(
enctype => 'multipart/form-data',
method => 'post',
fields => [qw(filename)]
);
$form->field(name => 'filename', type => 'file');
and then get to your file the same way as CGI.pm:
if ($form->submitted) {
my $file = $form->field('filename');
# save contents in file, etc ...
open F, ">$dir/$file" or die $!;
while (<$file>) {
print F;
}
close F;
print $form->confirm(header => 1);
} else {
print $form->render(header => 1);
}
in fact, that's a whole file upload program right there. ate and left no crumbs π β¨
π 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, i promise π«Ά
when you take a reference, you're basically turning something into a scalar value. sort of. you have to do this if you wanna 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's 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. less typing, more slay β¨
π± ENVIRONMENT VARIABLES
π FORMBUILDER_DEBUG
this toggles the debug flag, so that you can control FormBuilder debugging globally. helpful in mod_perl. π οΈ
π NOTES
parameters beginning with a leading underscore are reserved for future use by this module. use at your own peril. π like, seriously, that's a "you were warned" moment.
the field() method has the alias param() for compatibility with other modules, allowing you to pass a $form around just like a $cgi object. cute, right? π«Ά
the output of the HTML generated natively may change slightly from release to release. if you need precise control, use a template. periodt π
every attempt has been made to make this module taint-safe (-T). however, due to the way tainting works, you may run into the message "Insecure dependency" or "Insecure $ENV{PATH}". if so, make sure you are setting $ENV{PATH} at the top of your script. π₯
π ACKNOWLEDGEMENTS π
okay so this module literally blew up in the best way possible, and that's thanks to all the amazing people who sent in useful input, bug reports, and hype that kept it going. The full shout-out list, no cap:
- Norton Allen
- Mark Belanger
- Peter Billam
- Brad Bowman
- Jonathan Buhacoff
- Godfrey Carnegie
- Jakob Curdes
- Laurent Dami
- Bob Egert
- Peter Eichman
- Adam Foxson
- Jorge Gonzalez
- Florian Helmberger
- Mark Hedges
- Mark Houliston
- Victor Igumnov
- Robert James Kaes
- Dimitry Kharitonov
- Randy Kobes
- William Large
- Kevin Lubic
- Robert Mathews
- Mehryar
- Klaas Naajikens
- Koos Pol
- Shawn Poulson
- Victor Porton
- Dan Collis Puro
- Wolfgang Radke
- David Siegal
- Stephan Springl
- Ryan Tate
- John Theus
- Remi Turboult
- Andy Wardley
- Raphael Wegmann
- Emanuele Zeppieri
Thanks! π«Ά Like genuinely, thank you, every single one of you π
π SEE ALSO π
the whole friend group, go say hi:
CGI::FormBuilder::TemplateCGI::FormBuilder::MessagesCGI::FormBuilder::MultiCGI::FormBuilder::Source::FileCGI::FormBuilder::FieldCGI::FormBuilder::UtilCGI::FormBuilder::UtilHTML::TemplateText::Template CGI::FastTemplate
(yes, CGI::FormBuilder::Util is in there twice β that's literally how the page says it, so it stays π
)
π AUTHOR π
Copyright (c) Nate Wiger <http://nateware.com>. All Rights Reserved.
Nate Wiger is the original author; he kindly passed maintainership over to David Precious ("BIGPRESH") in 2016. King behavior honestly π
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.
ngl that's the whole page bestie π go build something iconic with it β¨
this was perl v5.42.2, dated 2024-09-19 β mwah, bye! π
π¦ where this page comes from
- alpine 3.24: perl-cgi-formbuilder-doc 3.20-r0 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms