# man > CGI::FormBuilder

---
type: CommandReference
command: CGI::FormBuilder
mode: perldoc
section: 3pm
source: perldoc
---

## Quick Reference
- `my $form = CGI::FormBuilder->new(fields => [qw(name email)], validate => { email => 'EMAIL' });` — create a form with fields and validation  
- `my $email = $form->field('email');` — get submitted value for a field  
- `if ($form->submitted && $form->validate) { ... }` — check submission and server-side validation  
- `print $form->render;` — output the form HTML  
- `$form->render(template => 'userinfo.tmpl');` — use a custom template layout  
- `$form->field(name => 'state', options => \@states);` — add a select/radio field with options  
- `$form->render(submit => ['Place Order', 'Cancel']);` — create multiple submit buttons  
- `$form->mailresults(to => 'user@example.com');` — email the form results  

## Name
Easily generate and process stateful forms

## Synopsis
perl
use CGI::FormBuilder;

my $form = CGI::FormBuilder->new(
    name      => 'contact',
    fields    => [qw(name email message)],
    validate  => { email => 'EMAIL' },
    method    => 'post',
    template  => 'contact.tmpl',
    header    => 1,
    submit    => 'Send',
);

if ($form->submitted && $form->validate) {
    print $form->confirm;
    # process $form->fields
} else {
    print $form->render;
}
## Options

### `new()` – constructor
- **`fields`** — arrayref of field names (required). e.g. `[qw(name email)]`. Also accepts a hashref (order not preserved).
- **`validate`** — hashref of field validation rules. Each value can be a regex (single‑quoted), a built‑in pattern (`'EMAIL'`, `'ZIPCODE'`, …), a subref, or a hash with `javascript`/`perl` keys. Toggles required status unless overridden.
- **`template`** — path to an `HTML::Template` file, a hashref of template options, a subroutine reference, or an object with a `render()` method.
- **`submit`** — text for a single submit button, or arrayref of labels for multiple buttons.
- **`method`** — `'post'` or `'get'` (default `'get'`).
- **`name`** — form name; used for JavaScript and HTML IDs (useful for multi‑form pages).
- **`header`** — boolean: output `Content-type` header and HTML preamble (default 0).
- **`title`** — title string shown above the form.
- **`required`** — arrayref of required fields, or `'ALL'` / `'NONE'`.
- **`values`** — hashref of default field values (overridden by CGI if sticky).
- **`stylesheet`** — 1 to enable CSS classes, or a path to a stylesheet (inserts `<link>`). Classes: `fb`, `fb_label`, `fb_field`, etc.
- **`keepextras`** — 1 to preserve unknown CGI parameters as hidden fields, or an arrayref of names to keep.
- **`javascript`** — 1 generates client‑side validation code (default 1).
- **`sticky`** — 1 keeps submitted values in the form (default 1).
- **`debug`** — 0‑3, increasing verbosity.
- **`params`** — object with a `param()` method (e.g., a custom CGI object); overrides `CGI.pm`.

### `field()` – field manipulation
- **`name`** — field name (required); first argument if sole option.
- **`label`** — display label; auto‑generated from name if omitted.
- **`type`** — input type: `text`, `textarea`, `password`, `hidden`, `select`, `radio`, `checkbox`, `file`. Auto‑detected based on options and multiple setting.
- **`options`** — arrayref of choices for selects/radios/checkboxes. Supports `[value => label]` pairs or complex structures.
- **`value`** — default value(s); use `force` to override CGI.
- **`force`** — boolean; when true, `value` overrides submitted data.
- **`multiple`** — allow multiple selections (checkboxes or multi‑select).
- **`validate`** — per‑field validation regex (single‑quoted).
- **`required`** — boolean for mandatory field.
- **`size`**, **`maxlength`**, **`cols`**, **`rows`** — HTML size attributes.
- **`comment`** — text displayed after the field.
- **`growable`** — 1 (or max limit) to let users add extra text/file inputs dynamically.
- **`other`** — 1 to append an “Other:” text input next to the field.
- **`sortopts`** — `'NAME'`, `'NUM'`, `1`, or subref to sort options.
- **`optgroups`** — 1 or hashref to group select options into `<optgroup>` elements.
- Any valid HTML attribute can be passed directly (e.g., `class`, `onchange`).

### Other Methods
- **`render(%options)`** — returns form HTML string. Accepts any `new()` option to override temporarily.
- **`validate(%extra_rules)`** — validates the form; returns true if all constraints pass. Extra rules can be added on the fly.
- **`submitted($watch_field)`** — returns the value of the clicked submit button, or true if `$watch_field` is present.
- **`confirm(%options)`** — renders a static confirmation screen; `template` can differ from the form.
- **`mailresults(%options)`** — emails form data. Options: `to`, `from`, `delimiter`, `joiner`, `plugin` (for custom mailers).
- **`sessionid($id)`** — get/set a session identifier stored in `_sessionid`; automatic cookie if `header` is set.
- **`cgi_param($name)`** — access non‑field CGI parameters (e.g., `mode`).
- **`prepare()`** — returns a hash of expanded template variables, useful for custom rendering.
- **`tmpl_param($name => $value)`** — pass extra template variables.

## Examples

### Order Form with Validation
perl
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(
    fields => [qw(first_name last_name email credit_card expiration)],
    validate => {
        email       => 'EMAIL',
        credit_card => 'CARD',
        expiration  => 'MMYY',
    },
    submit => ['Place Order', 'Cancel'],
    header => 1,
);
if ($form->submitted eq 'Cancel') {
    print $form->cgi->redirect('/');
} elsif ($form->submitted && $form->validate) {
    print $form->confirm;
} else {
    print $form->render;
}
### Pre‑populate from Database
perl
use DBI;
my $dbh = DBI->connect(...);
my $sth = $dbh->prepare("SELECT * FROM users WHERE id = ?");
$sth->execute($user_id);
my $row = $sth->fetchrow_hashref;
my $form = CGI::FormBuilder->new(fields => [qw(name email phone)]);
print $form->render(values => $row, header => 1);
### Session‑Avare Form
perl
use CGI::Session;
use CGI::FormBuilder;
my $form = CGI::FormBuilder->new(fields => \@fields, header => 1);
my $session = CGI::Session->new('driver:File', $form->sessionid, {Directory=>'/tmp'});
if ($form->submitted && $form->validate) {
    $session->save_param($form);
}
$form->sessionid($session->id);
print $form->render;
## See Also
- [CGI::FormBuilder::Template](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3ATemplate/markdown) – template engine integration
- [CGI::FormBuilder::Messages](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3AMessages/markdown) – internationalisation
- [CGI::FormBuilder::Multi](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3AMulti/markdown) – multi‑page form wizard
- [CGI::FormBuilder::Source::File](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3ASource%3A%3AFile/markdown) – external configuration
- [CGI::FormBuilder::Field](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3AField/markdown) – field internals
- [CGI::FormBuilder::Util](http://localhost/phpMan.php/perldoc/CGI%3A%3AFormBuilder%3A%3AUtil/markdown) – utility routines
- [HTML::Template](http://localhost/phpMan.php/perldoc/HTML%3A%3ATemplate/markdown) – default template engine
- [CGI::FormBuilder website](http://formbuilder.org) – tutorials and examples