{
    "content": [
        {
            "type": "text",
            "text": "# CGI::FormBuilder (perldoc)\n\n## NAME\n\nCGI::FormBuilder - Easily generate and process stateful forms\n\n## SYNOPSIS\n\nuse CGI::FormBuilder;\n# Assume we did a DBI query to get existing values\nmy $dbval = $sth->fetchrowhashref;\n# First create our form\nmy $form = CGI::FormBuilder->new(\nname     => 'acctinfo',\nmethod   => 'post',\nstylesheet => '/path/to/style.css',\nvalues   => $dbval,   # defaults\n);\n# Now create form fields, in order\n# FormBuilder will automatically determine the type for you\n$form->field(name => 'fname', label => 'First Name');\n$form->field(name => 'lname', label => 'Last Name');\n# Setup gender field to have options\n$form->field(name => 'gender',\noptions => [qw(Male Female)] );\n# Include validation for the email field\n$form->field(name => 'email',\nsize => 60,\nvalidate => 'EMAIL',\nrequired => 1);\n# And the (optional) phone field\n$form->field(name => 'phone',\nsize => 10,\nvalidate => '/^1?-?\\d{3}-?\\d{3}-?\\d{4}$/',\ncomment  => '<i>optional</i>');\n# Check to see if we're submitted and valid\nif ($form->submitted && $form->validate) {\n# Get form fields as hashref\nmy $field = $form->fields;\n# Do something to update your data (you would write this)\ndodataupdate($field->{lname}, $field->{fname},\n$field->{email}, $field->{phone},\n$field->{gender});\n# Show confirmation screen\nprint $form->confirm(header => 1);\n} else {\n# Print out the form\nprint $form->render(header => 1);\n}\n\n## DESCRIPTION\n\nIf this is your first time using FormBuilder, you should check out the website for tutorials and\nexamples at <http://formbuilder.org>.\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **DESCRIPTION** (3 subsections)\n- **METHODS**\n- **COMPATIBILITY**\n- **EXAMPLES** (6 subsections)\n- **REFERENCES**\n- **ENVIRONMENT VARIABLES**\n- **NOTES**\n- **ACKNOWLEDGEMENTS**\n- **SEE ALSO**\n- **REVISION**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "CGI::FormBuilder",
        "section": "",
        "mode": "perldoc",
        "summary": "CGI::FormBuilder - Easily generate and process stateful forms",
        "synopsis": "use CGI::FormBuilder;\n# Assume we did a DBI query to get existing values\nmy $dbval = $sth->fetchrowhashref;\n# First create our form\nmy $form = CGI::FormBuilder->new(\nname     => 'acctinfo',\nmethod   => 'post',\nstylesheet => '/path/to/style.css',\nvalues   => $dbval,   # defaults\n);\n# Now create form fields, in order\n# FormBuilder will automatically determine the type for you\n$form->field(name => 'fname', label => 'First Name');\n$form->field(name => 'lname', label => 'Last Name');\n# Setup gender field to have options\n$form->field(name => 'gender',\noptions => [qw(Male Female)] );\n# Include validation for the email field\n$form->field(name => 'email',\nsize => 60,\nvalidate => 'EMAIL',\nrequired => 1);\n# And the (optional) phone field\n$form->field(name => 'phone',\nsize => 10,\nvalidate => '/^1?-?\\d{3}-?\\d{3}-?\\d{4}$/',\ncomment  => '<i>optional</i>');\n# Check to see if we're submitted and valid\nif ($form->submitted && $form->validate) {\n# Get form fields as hashref\nmy $field = $form->fields;\n# Do something to update your data (you would write this)\ndodataupdate($field->{lname}, $field->{fname},\n$field->{email}, $field->{phone},\n$field->{gender});\n# Show confirmation screen\nprint $form->confirm(header => 1);\n} else {\n# Print out the form\nprint $form->render(header => 1);\n}",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [
            "I find this module incredibly useful, so here are even more examples, pasted from sample code",
            "that I've written:",
            "This example provides an order form, complete with validation of the important fields, and a",
            "\"Cancel\" button to abort the whole thing.",
            "#!/usr/bin/perl",
            "use strict;",
            "use CGI::FormBuilder;",
            "my @states = mystatelist();   # you write this",
            "my $form = CGI::FormBuilder->new(",
            "method => 'post',",
            "fields => [",
            "qw(firstname lastname",
            "email sendmeemails",
            "address state zipcode",
            "creditcard expiration)",
            "],",
            "header => 1,",
            "title  => 'Finalize Your Order',",
            "submit => ['Place Order', 'Cancel'],",
            "reset  => 0,",
            "validate => {",
            "email   => 'EMAIL',",
            "zipcode => 'ZIPCODE',",
            "creditcard => '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    => 'sendmeemails',",
            "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 will provide a pulldown menu for the",
            "\"state\", a radio group for \"sendmeemails\", and normal text boxes for the rest. It will then",
            "validate all the fields, using specific patterns for those fields specified to \"validate\".",
            "Here's an example that adds some fields dynamically, and uses the \"debug\" option spit out gook:",
            "#!/usr/bin/perl",
            "use strict;",
            "use CGI::FormBuilder;",
            "my $form = CGI::FormBuilder->new(",
            "method => 'post',",
            "fields => [",
            "qw(firstname lastname 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 username with validation",
            "$form->field(name  => 'username',",
            "value => $ENV{REMOTEUSER},",
            "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 \"username\" field will still be validated",
            "if filled in.",
            "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",
            "use strict;",
            "use CGI::FormBuilder;",
            "my $form = CGI::FormBuilder->new(",
            "fields => [qw(type string status category)],",
            "header => 1,",
            "template => 'ticketsearch.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 recentlycompleted 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 \"ticketsearch.tmpl\" HTML file, we would have something like this:",
            "<html>",
            "<head>",
            "<title>Search Engine</title>",
            "<tmplvar js-head>",
            "</head>",
            "<body bgcolor=\"white\">",
            "<center>",
            "<p>",
            "Please enter a term to search the ticket database.",
            "<p>",
            "<tmplvar form-start>",
            "Search by <tmplvar field-type> for <tmplvar field-string>",
            "<tmplvar form-submit>",
            "<p>",
            "Status: <tmplvar field-status>",
            "<p>",
            "Category: <tmplvar 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.",
            "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 confirmpassword",
            "firstname lastname email)]",
            ");",
            "# Now get the value of the username from our app",
            "my $user = $form->cgiparam('user');",
            "my $sth = $dbh->prepare(\"select * from userinfo where user = '$user'\");",
            "$sth->execute;",
            "my $defaulthashref = $sth->fetchrowhashref;",
            "# Render our form with the defaults we got in our hashref",
            "print $form->render(values => $defaulthashref,",
            "title  => \"User information for '$user'\",",
            "header => 1);",
            "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",
            "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.",
            "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->saveparam($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.",
            "FREQUENTLY ASKED QUESTIONS (FAQ)",
            "There are a couple questions and subtle traps that seem to poke people on a regular basis. Here",
            "are some hints.",
            "I'm confused. Why doesn't this work like CGI.pm?",
            "If you're used to \"CGI.pm\", you have to do a little bit of a brain shift when working with this",
            "module.",
            "FormBuilder 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 for the data you want to",
            "collect. The HTML representation is just one property of this field.",
            "So, if you want a single-option checkbox, simply say something like this:",
            "$form->field(name    => 'joinmailinglist',",
            "options => ['Yes']);",
            "If you want it to be checked by default, you add the \"value\" arg:",
            "$form->field(name    => 'joinmailinglist',",
            "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    => 'joinmailinglist',",
            "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 much more flexibility and less code maintenance. If you",
            "want to be able to accept multiple values, simply use the \"multiple\" arg:",
            "$form->field(name     => 'favoritecolors',",
            "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('favoritecolors');",
            "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",
            "\"cgiparam()\" method:",
            "my $mode = $form->cgiparam('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');",
            "# 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 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');",
            "# 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 \"cgiparam()\" function, you could also modify your code so you",
            "use FormBuilder exclusively, as in the previous question.",
            "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->cgiparam('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 = selectvalues();",
            "$form->values(\\%values);",
            "print $form->render;",
            "Using the accessors makes permanent changes to your object, so be aware that if you want to",
            "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.",
            "How do I manually override the value of a field?",
            "You must specify the \"force\" option:",
            "$form->field(name  => 'nameoffield',",
            "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.",
            "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 will still be able to access the values, but they won't",
            "show up in the form.",
            "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()\":",
            "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."
        ],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 51,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 7,
                "subsections": [
                    {
                        "name": "Overview",
                        "lines": 35
                    },
                    {
                        "name": "Quick Reference",
                        "lines": 114
                    },
                    {
                        "name": "Walkthrough",
                        "lines": 165
                    }
                ]
            },
            {
                "name": "METHODS",
                "lines": 1326,
                "subsections": []
            },
            {
                "name": "COMPATIBILITY",
                "lines": 89,
                "subsections": []
            },
            {
                "name": "EXAMPLES",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Ex1: order.cgi",
                        "lines": 66
                    },
                    {
                        "name": "Ex2: orderform.cgi",
                        "lines": 39
                    },
                    {
                        "name": "Ex3: ticketsearch.cgi",
                        "lines": 59
                    },
                    {
                        "name": "Ex4: userinfo.cgi",
                        "lines": 30
                    },
                    {
                        "name": "Ex5: addpart.cgi",
                        "lines": 47
                    },
                    {
                        "name": "Ex6: Session Management",
                        "lines": 241
                    }
                ]
            },
            {
                "name": "REFERENCES",
                "lines": 50,
                "subsections": []
            },
            {
                "name": "ENVIRONMENT VARIABLES",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 13,
                "subsections": []
            },
            {
                "name": "ACKNOWLEDGEMENTS",
                "lines": 43,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "REVISION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "CGI::FormBuilder - Easily generate and process stateful forms\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use CGI::FormBuilder;\n\n# Assume we did a DBI query to get existing values\nmy $dbval = $sth->fetchrowhashref;\n\n# First create our form\nmy $form = CGI::FormBuilder->new(\nname     => 'acctinfo',\nmethod   => 'post',\nstylesheet => '/path/to/style.css',\nvalues   => $dbval,   # defaults\n);\n\n# Now create form fields, in order\n# FormBuilder will automatically determine the type for you\n$form->field(name => 'fname', label => 'First Name');\n$form->field(name => 'lname', label => 'Last Name');\n\n# Setup gender field to have options\n$form->field(name => 'gender',\noptions => [qw(Male Female)] );\n\n# Include validation for the email field\n$form->field(name => 'email',\nsize => 60,\nvalidate => 'EMAIL',\nrequired => 1);\n\n# And the (optional) phone field\n$form->field(name => 'phone',\nsize => 10,\nvalidate => '/^1?-?\\d{3}-?\\d{3}-?\\d{4}$/',\ncomment  => '<i>optional</i>');\n\n# Check to see if we're submitted and valid\nif ($form->submitted && $form->validate) {\n# Get form fields as hashref\nmy $field = $form->fields;\n\n# Do something to update your data (you would write this)\ndodataupdate($field->{lname}, $field->{fname},\n$field->{email}, $field->{phone},\n$field->{gender});\n\n# Show confirmation screen\nprint $form->confirm(header => 1);\n} else {\n# Print out the form\nprint $form->render(header => 1);\n}\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "If this is your first time using FormBuilder, you should check out the website for tutorials and\nexamples at <http://formbuilder.org>.\n\nYou should also consider joining the google group at\n<http://groups.google.com/group/perl-formbuilder>. There are some pretty smart people on the\nlist that can help you out.\n",
                "subsections": [
                    {
                        "name": "Overview",
                        "content": "I hate generating and processing forms. Hate it, hate it, hate it, hate it. My forms almost\nalways end up looking the same, and almost always end up doing the same thing. Unfortunately,\nthere haven't really been any tools out there that streamline the process. Many modules simply\nsubstitute Perl for HTML code:\n\n# The manual way\nprint qq(<input name=\"email\" type=\"text\" size=\"20\">);\n\n# The module way\nprint input(-name => 'email', -type => 'text', -size => '20');\n\nThe problem is, that doesn't really gain you anything - you still have just as much code.\nModules like \"CGI.pm\" are great for decoding parameters, but not for generating and processing\nwhole forms.\n\nThe goal of CGI::FormBuilder (FormBuilder) is to provide an easy way for you to generate and\nprocess entire CGI form-based applications. Its main features are:\n\nField Abstraction\nViewing fields as entities (instead of just params), where the HTML representation, CGI\nvalues, validation, and so on are properties of each field.\n\nDWIMmery\nLots of built-in \"intelligence\" (such as automatic field typing), giving you about a 4:1\nratio of the code it generates versus what you have to write.\n\nBuilt-in Validation\nFull-blown regex validation for fields, even including JavaScript code generation.\n\nTemplate Support\nPluggable support for external template engines, such as \"HTML::Template\", \"Text::Template\",\n\"Template Toolkit\", and \"CGI::FastTemplate\".\n\nPlus, the native HTML generated is valid XHTML 1.0 Transitional.\n"
                    },
                    {
                        "name": "Quick Reference",
                        "content": "For the incredibly impatient, here's the quickest reference you can get:\n\n# Create form\nmy $form = CGI::FormBuilder->new(\n\n# Important options\nfields     => \\@array | \\%hash,   # define form fields\nheader     => 0 | 1,              # send Content-type?\nmethod     => 'post' | 'get',     # default is get\nname       => $string,            # namespace (recommended)\nreset      => 0 | 1 | $str,            # \"Reset\" button\nsubmit     => 0 | 1 | $str | \\@array,  # \"Submit\" button(s)\ntext       => $text,              # printed above form\ntitle      => $title,             # printed up top\nrequired   => \\@array | 'ALL' | 'NONE',  # required fields?\nvalues     => \\%hash | \\@array,   # from DBI, session, etc\nvalidate   => \\%hash,             # automatic field validation\n\n# Lesser-used options\naction     => $script,            # not needed (loops back)\ncookies    => 0 | 1,              # use cookies for sessionid?\ndebug      => 0 | 1 | 2 | 3,      # gunk into errorlog?\nfieldsubs  => 0 | 1,              # allow $form->$field()\njavascript => 0 | 1 | 'auto',     # generate JS validate() code?\nkeepextras => 0 | 1 | \\@array,    # keep non-field params?\nparams     => $object,            # instead of CGI.pm\nsticky     => 0 | 1,              # keep CGI values \"sticky\"?\nmessages   => $file | \\%hash | $locale | 'auto',\ntemplate   => $file | \\%hash | $object,   # custom HTML\n\n# HTML formatting and JavaScript options\nbody       => \\%attr,             # {background => 'black'}\ndisabled   => 0 | 1,              # display as grayed-out?\nfieldsets  => \\@arrayref          # split form into <fieldsets>\nfont       => $font | \\%attr,     # 'arial,helvetica'\njsfunc     => $jscode,            # JS code into validate()\njshead     => $jscode,            # JS code into <head>\nlinebreaks => 0 | 1,              # put breaks in form?\nselectnum  => $threshold,         # for auto-type generation\nsmartness  => 0 | 1 | 2,          # tweak \"intelligence\"\nstatic     => 0 | 1 | 2,          # show non-editable form?\nstyleclass => $string,            # style class to use (\"fb\")\nstylesheet => 0 | 1 | $path,      # turn on style class=\ntable      => 0 | 1 | \\%attr,     # wrap form in <table>?\ntd         => \\%attr,             # <td> options\ntr         => \\%attr,             # <tr> options\n\n# These are deprecated and you should use field() instead\nfieldtype  => 'type',\nfieldattr  => \\%attr,\nlabels     => \\%hash,\noptions    => \\%hash,\nsortopts   => 'NAME' | 'NUM' | 1 | \\&sub,\n\n# External source file (see CGI::FormBuilder::Source::File)\nsource     => $file,\n);\n\n# Tweak fields individually\n$form->field(\n\n# Important options\nname       => $name,          # name of field (required)\nlabel      => $string,        # shown in front of <input>\ntype       => $type,          # normally auto-determined\nmultiple   => 0 | 1,          # allow multiple values?\noptions    => \\@options | \\%options,   # radio/select/checkbox\nvalue      => $value | \\@values,       # default value\n\n# Lesser-used options\nfieldset   => $string,        # put field into <fieldset>\nforce      => 0 | 1,          # override CGI value?\ngrowable   => 0 | 1 | $limit, # expand text/file inputs?\njsclick    => $jscode,        # instead of onclick\njsmessage  => $string,        # on JS validation failure\nmessage    => $string,        # other validation failure\nother      => 0 | 1,          # create \"Other:\" input?\nrequired   => 0 | 1,          # must fill field in?\nvalidate   => '/regex/',      # validate user input\n\n# HTML formatting options\ncleanopts  => 0 | 1,          # HTML-escape options?\ncolumns    => 0 | $width,     # wrap field options at $width\ncomment    => $string,        # printed after field\ndisabled   => 0 | 1,          # display as grayed-out?\nlabels     => \\%hash,         # deprecated (use \"options\")\nlinebreaks => 0 | 1,          # insert breaks in options?\nnameopts   => 0 | 1,          # auto-name options?\nsortopts   => 'NAME' | 'NUM' | 1 | \\&sub,   # sort options?\n\n# Change size, maxlength, or any other HTML attr\n$htmlattr  => $htmlval,\n);\n\n# Check for submission\nif ($form->submitted && $form->validate) {\n\n# Get single value\nmy $value = $form->field('name');\n\n# Get list of fields\nmy @field = $form->field;\n\n# Get hashref of key/value pairs\nmy $field = $form->field;\nmy $value = $field->{name};\n\n}\n\n# Print form\nprint $form->render(anyoptfromnew => $somevalue);\n\nThat's it. Keep reading.\n"
                    },
                    {
                        "name": "Walkthrough",
                        "content": "Let's walk through a whole example to see how FormBuilder works. We'll start with this, which is\nactually a complete (albeit simple) form application:\n\nuse CGI::FormBuilder;\n\nmy @fields = qw(name email password confirmpassword zipcode);\n\nmy $form = CGI::FormBuilder->new(\nfields => \\@fields,\nheader => 1\n);\n\nprint $form->render;\n\nThe above code will render an entire form, and take care of maintaining state across\nsubmissions. But it doesn't really *do* anything useful at this point.\n\nSo to start, let's add the \"validate\" option to make sure the data entered is valid:\n\nmy $form = CGI::FormBuilder->new(\nfields   => \\@fields,\nheader   => 1,\nvalidate => {\nname  => 'NAME',\nemail => 'EMAIL'\n}\n);\n\nWe now get a whole bunch of JavaScript validation code, and the appropriate hooks are added so\nthat the form is validated by the browser \"onsubmit\" as well.\n\nNow, we also want to validate our form on the server side, since the user may not be running\nJavaScript. All we do is add the statement:\n\n$form->validate;\n\nWhich will go through the form, checking each field specified to the \"validate\" option to see if\nit's ok. If there's a problem, then that field is highlighted, so that when you print it out the\nerrors will be apparent.\n\nOf course, the above returns a truth value, which we should use to see if the form was valid.\nThat way, we only update our database if everything looks good:\n\nif ($form->validate) {\n# print confirmation screen\nprint $form->confirm;\n} else {\n# print the form for them to fill out\nprint $form->render;\n}\n\nHowever, we really only want to do this after our form has been submitted, since otherwise this\nwill result in our form showing errors even though the user hasn't gotten a chance to fill it\nout yet. As such, we want to check for whether the form has been \"submitted()\" yet:\n\nif ($form->submitted && $form->validate) {\n# print confirmation screen\nprint $form->confirm;\n} else {\n# print the form for them to fill out\nprint $form->render;\n}\n\nNow that know that our form has been submitted and is valid, we need to get our values. To do\nso, we use the \"field()\" method along with the name of the field we want:\n\nmy $email = $form->field(name => 'email');\n\nNote we can just specify the name of the field if it's the only option:\n\nmy $email = $form->field('email');   # same thing\n\nAs a very useful shortcut, we can get all our fields back as a hashref of field/value pairs by\ncalling \"field()\" with no arguments:\n\nmy $fields = $form->field;      # all fields as hashref\n\nTo make things easy, we'll use this form so that we can pass it easily into a sub of our\nchoosing:\n\nif ($form->submitted && $form->validate) {\n# form was good, let's update database\nmy $fields = $form->field;\n\n# update database (you write this part)\ndodataupdate($fields);\n\n# print confirmation screen\nprint $form->confirm;\n}\n\nFinally, let's say we decide that we like our form fields, but we need the HTML to be laid out\nvery precisely. No problem! We simply create an \"HTML::Template\" compatible template and tell\nFormBuilder to use it. Then, in our template, we include a couple special tags which FormBuilder\nwill automatically expand:\n\n<html>\n<head>\n<title><tmplvar form-title></title>\n<tmplvar js-head><!-- this holds the JavaScript code -->\n</head>\n<tmplvar form-start><!-- this holds the initial form tag -->\n<h3>User Information</h3>\nPlease fill out the following information:\n<!-- each of these tmplvar's corresponds to a field -->\n<p>Your full name: <tmplvar field-name>\n<p>Your email address: <tmplvar field-email>\n<p>Choose a password: <tmplvar field-password>\n<p>Please confirm it: <tmplvar field-confirmpassword>\n<p>Your home zipcode: <tmplvar field-zipcode>\n<p>\n<tmplvar form-submit><!-- this holds the form submit button -->\n</form><!-- can also use \"tmplvar form-end\", same thing -->\n\nThen, all we need to do add the \"template\" option, and the rest of the code stays the same:\n\nmy $form = CGI::FormBuilder->new(\nfields   => \\@fields,\nheader   => 1,\nvalidate => {\nname  => 'NAME',\nemail => 'EMAIL'\n},\ntemplate => 'userinfo.tmpl'\n);\n\nSo, our complete code thus far looks like this:\n\nuse CGI::FormBuilder;\n\nmy @fields = qw(name email password confirmpassword zipcode);\n\nmy $form = CGI::FormBuilder->new(\nfields   => \\@fields,\nheader   => 1,\nvalidate => {\nname  => 'NAME',\nemail => 'EMAIL'\n},\ntemplate => 'userinfo.tmpl',\n);\n\nif ($form->submitted && $form->validate) {\n# form was good, let's update database\nmy $fields = $form->field;\n\n# update database (you write this part)\ndodataupdate($fields);\n\n# print confirmation screen\nprint $form->confirm;\n\n} else {\n# print the form for them to fill out\nprint $form->render;\n}\n\nYou may be surprised to learn that for many applications, the above is probably all you'll need.\nJust fill in the parts that affect what you want to do (like the database code), and you're on\nyour way.\n\nNote: If you are confused at all by the backslashes you see in front of some data pieces above,\nsuch as \"\\@fields\", skip down to the brief section entitled \"REFERENCES\" at the bottom of this\ndocument (it's short).\n"
                    }
                ]
            },
            "METHODS": {
                "content": "This documentation is very extensive, but can be a bit dizzying due to the enormous number of\noptions that let you tweak just about anything. As such, I recommend that you stop and visit:\n\nwww.formbuilder.org\n\nAnd click on \"Tutorials\" and \"Examples\". Then, use the following section as a reference later\non.\n\nnew()\nThis method creates a new $form object, which you then use to generate and process your form. In\nthe very shortest version, you can just specify a list of fields for your form:\n\nmy $form = CGI::FormBuilder->new(\nfields => [qw(firstname birthday favoritecar)]\n);\n\nAs of 3.02:\n\nmy $form = CGI::FormBuilder->new(\nsource => 'myform.conf'   # form and field options\n);\n\nFor details on the external file format, see CGI::FormBuilder::Source::File.\n\nAny of the options below, in addition to being specified to \"new()\", can also be manipulated\ndirectly with a method of the same name. For example, to change the \"header\" and \"stylesheet\"\noptions, either of these works:\n\n# Way 1\nmy $form = CGI::FormBuilder->new(\nfields => \\@fields,\nheader => 1,\nstylesheet => '/path/to/style.css',\n);\n\n# Way 2\nmy $form = CGI::FormBuilder->new(\nfields => \\@fields\n);\n$form->header(1);\n$form->stylesheet('/path/to/style.css');\n\nThe second form is useful if you want to wrap certain options in conditionals:\n\nif ($havetemplate) {\n$form->header(0);\n$form->template('template.tmpl');\n} else {\n$form->header(1);\n$form->stylesheet('/path/to/style.css');\n}\n\nThe following is a description of each option, in alphabetical order:\n\naction => $script\nWhat script to point the form to. Defaults to itself, which is the recommended setting.\n\nbody => \\%attr\nThis takes a hashref of attributes that will be stuck in the \"<body>\" tag verbatim (for\nexample, bgcolor, alink, etc). See the \"fieldattr\" tag for more details, and also the\n\"template\" option.\n\ncharset\nThis forcibly overrides the charset. Better handled by loading an appropriate \"messages\"\nmodule, which will set this for you. See CGI::FormBuilder::Messages for more details.\n\ndebug => 0 | 1 | 2 | 3\nIf set to 1, the module spits copious debugging info to STDERR. If set to 2, it spits out\neven more gunk. 3 is too much. Defaults to 0.\n\nfields => \\@array | \\%hash\nAs shown above, the \"fields\" option takes an arrayref of fields to use in the form. The\nfields will be printed out in the same order they are specified. This option is needed if\nyou expect your form to have any fields, and is *the* central option to FormBuilder.\n\nYou can also specify a hashref of key/value pairs. The advantage is you can then bypass the\n\"values\" option. However, the big disadvantage is you cannot control the order of the\nfields. This is ok if you're using a template, but in real-life it turns out that passing a\nhashref to \"fields\" is not very useful.\n\nfieldtype => 'type'\nThis can be used to set the default type for all fields in the form. You can then override\nit on a per-field basis using the \"field()\" method.\n\nfieldattr => \\%attr\nThis option allows you to specify *any* HTML attribute and have it be the default for all\nfields. This used to be good for stylesheets, but now that there is a \"stylesheet\" option,\nthis is fairly useless.\n\nfieldsets => \\@attr\nThis allows you to define fieldsets for your form. Fieldsets are used to group fields\ntogether. Fields are rendered in order, inside the fieldset they belong to. If a field does\nnot have a fieldset, it is appended to the end of the form.\n\nTo use fieldsets, specify an arrayref of \"<fieldset>\" names:\n\nfieldsets => [qw(account preferences contacts)]\n\nYou can get a different \"<legend>\" tag if you specify a nested arrayref:\n\nfieldsets => [\n[ account  => 'Account Information' ],\n[ preferences => 'Website Preferences' ],\n[ contacts => 'Email and Phone Numbers' ],\n]\n\nIf you're using the source file, that looks like this:\n\nfieldsets: account=Account Information,preferences=...\n\nThen, for each field, specify which fieldset it belongs to:\n\n$form->field(name => 'firstname', fieldset => 'account');\n$form->field(name => 'lastname',  fieldset => 'account');\n$form->field(name => 'emailme',   fieldset => 'preferences');\n$form->field(name => 'homephone', fieldset => 'contacts');\n$form->field(name => 'workphone', fieldset => 'contacts');\n\nYou can also automatically create a new \"fieldset\" on the fly by specifying a new one:\n\n$form->field(name => 'rememberme', fieldset => 'advanced');\n\nTo set the \"<legend>\" in this case, you have two options. First, you can just choose a more\nreadable \"fieldset\" name:\n\n$form->field(name => 'rememberme',\nfieldset => 'Advanced');\n\nOr, you can change the name using the \"fieldset\" accessor:\n\n$form->fieldset(advanced => 'Advanced Options');\n\nNote that fieldsets without fields are silently ignored, so you can also just specify a huge\nlist of possible fieldsets to \"new()\", and then only add fields as you need them.\n\nfieldsubs => 0 | 1\nThis allows autoloading of field names so you can directly access them as:\n\n$form->$fieldname(opt => 'val');\n\nInstead of:\n\n$form->field(name => $fieldname, opt => 'val');\n\nWarning: If present, it will hide any attributes of the same name. For example, if you\ndefine \"name\" field, you won't be able to change your form's name dynamically. Also, you\ncannot use this format to create new fields. Use with caution.\n\nfont => $font | \\%attr\nThe font face to use for the form. This is output as a series of \"<font>\" tags for old\nbrowser compatibility, and will properly nest them in all of the table elements. If you\nspecify a hashref instead of just a font name, then each key/value pair will be taken as\npart of the \"<font>\" tag:\n\nfont => {face => 'verdana', size => '-1', color => 'gray'}\n\nThe above becomes:\n\n<font face=\"verdana\" size=\"-1\" color=\"gray\">\n\nI used to use this all the time, but the \"stylesheet\" option is SO MUCH BETTER. Trust me,\ntake a day and learn the basics of CSS, it's totally worth it.\n\nheader => 0 | 1\nIf set to 1, a valid \"Content-type\" header will be printed out, along with a whole bunch of\nHTML \"<body>\" code, a \"<title>\" tag, and so on. This defaults to 0, since often people end\nup using templates or embedding forms in other HTML.\n\njavascript => 0 | 1\nIf set to 1, JavaScript is generated in addition to HTML, the default setting.\n\njserror => 'functionname'\nIf specified, this will get called instead of the standard JS \"alert()\" function on error.\nThe function signature is:\n\nfunctionname(form, invalid, alertstr, invalidfields)\n\nThe function can be named anything you like. A simple one might look like this:\n\nmy $form = CGI::FormBuilder->new(\njserror => 'fielderrors',\njshead => <<'EOJS',\nfunction fielderrors(form, invalid, alertstr, invalidfields) {\n// first reset all fields\nfor (var i=0; i < form.elements.length; i++) {\nform.elements[i].className = 'normalfield';\n}\n// now attach a special style class to highlight the field\nfor (var i=0; i < invalidfields.length; i++) {\nform.elements[invalidfields[i]].className = 'invalidfield';\n}\nalert(alertstr);\nreturn false;\n}\nEOJS\n);\n\nNote that it should return false to prevent form submission.\n\nThis can be used in conjunction with \"jsfunc\", which can add additional manual validations\nbefore \"jserror\" is called.\n\njsfunc => $jscode\nThis is verbatim JavaScript that will go into the \"validate\" JavaScript function. It is\nuseful for adding your own validation code, while still getting all the automatic hooks. If\nsomething fails, you should do two things:\n\n1. append to the JavaScript string \"alertstr\"\n2. increment the JavaScript number \"invalid\"\n\nFor example:\n\nmy $jsfunc = <<'EOJS';   # note single quote (see Hint)\nif (form.password.value == 'password') {\nalertstr += \"Moron, you can't use 'password' for your password!\\\\n\";\ninvalid++;\n}\nEOJS\n\nmy $form = CGI::FormBuilder->new(... jsfunc => $jsfunc);\n\nThen, this code will be automatically called when form validation is invoked. I find this\noption can be incredibly useful. Most often, I use it to bypass validation on certain submit\nmodes. The submit button that was clicked is \"form.submit.value\":\n\nmy $jsfunc = <<'EOJS';   # note single quotes (see Hint)\nif (form.submit.value == 'Delete') {\nif (confirm(\"Really DELETE this entry?\")) return true;\nreturn false;\n} else if (form.submit.value == 'Cancel') {\n// skip validation since we're cancelling\nreturn true;\n}\nEOJS\n\nHint: To prevent accidental expansion of embedding strings and escapes, you should put your\n\"HERE\" string in single quotes, as shown above.\n\njshead => $jscode\nIf using JavaScript, you can also specify some JavaScript code that will be included\nverbatim in the <head> section of the document. I'm not very fond of this one, what you\nprobably want is the previous option.\n\nkeepextras => 0 | 1 | \\@array\nIf set to 1, then extra parameters not set in your fields declaration will be kept as hidden\nfields in the form. However, you will need to use \"cgiparam()\", NOT \"field()\", to access\nthe values.\n\nThis is useful if you want to keep some extra parameters like mode or company available but\nnot have them be valid form fields:\n\nkeepextras => 1\n\nThat will preserve any extra params. You can also specify an arrayref, in which case only\nparams in that list will be preserved. For example:\n\nkeepextras => [qw(mode company)]\n\nWill only preserve the params \"mode\" and \"company\". Again, to access them:\n\nmy $mode = $form->cgiparam('mode');\n$form->cgiparam(name => 'mode', value => 'relogin');\n\nSee \"CGI.pm\" for details on \"param()\" usage.\n\nlabels => \\%hash\nLike \"values\", this is a list of key/value pairs where the keys are the names of \"fields\"\nspecified above. By default, FormBuilder does some snazzy case and character conversion to\ncreate pretty labels for you. However, if you want to explicitly name your fields, use this\noption.\n\nFor example:\n\nmy $form = CGI::FormBuilder->new(\nfields => [qw(name email)],\nlabels => {\nname  => 'Your Full Name',\nemail => 'Primary Email Address'\n}\n);\n\nUsually you'll find that if you're contemplating this option what you really want is a\ntemplate.\n\nlalign => 'left' | 'right' | 'center'\nA legacy shortcut for:\n\nth => { align => 'left' }\n\nEven better, use the \"stylesheet\" option and tweak the \".fblabel\" class. Either way, don't\nuse this.\n\nlang\nThis forcibly overrides the lang. Better handled by loading an appropriate \"messages\"\nmodule, which will set this for you. See CGI::FormBuilder::Messages for more details.\n\nmethod => 'post' | 'get'\nThe type of CGI method to use, either \"post\" or \"get\". Defaults to \"get\" if nothing is\nspecified. Note that for forms that cause changes on the server, such as database inserts,\nyou should use the \"post\" method.\n\nmessages => 'auto' | $file | \\%hash | $locale\nThis option overrides the default FormBuilder messages in order to provide multilingual\nlocale support (or just different text for the picky ones). For details on this option,\nplease refer to CGI::FormBuilder::Messages.\n\nname => $string\nThis names the form. It is optional, but when used, it renames several key variables and\nfunctions according to the name of the form. In addition, it also adds the following \"<div>\"\ntags to each row of the table:\n\n<tr id=\"${form}${field}row\">\n<td id=\"${form}${field}label\">Label</td>\n<td id=\"${form}${field}input\"><input tag></td>\n<td id=\"${form}${field}error\">Error</td><!-- if invalid -->\n</tr>\n\nThese changes allow you to (a) use multiple forms in a sequential application and/or (b)\ndisplay multiple forms inline in one document. If you're trying to build a complex\nmulti-form app and are having problems, try naming your forms.\n\noptions => \\%hash\nThis is one of several *meta-options* that allows you to specify stuff for multiple fields\nat once:\n\nmy $form = CGI::FormBuilder->new(\nfields => [qw(partnumber department instock)],\noptions => {\ndepartment => [qw(hardware software)],\ninstock   => [qw(yes no)],\n}\n);\n\nThis has the same effect as using \"field()\" for the \"department\" and \"instock\" fields to\nset options individually.\n\nparams => $object\nThis specifies an object from which the parameters should be derived. The object must have a\n\"param()\" method which will return values for each parameter by name. By default a CGI\nobject will be automatically created and used.\n\nHowever, you will want to specify this if you're using \"modperl\":\n\nuse Apache::Request;\nuse CGI::FormBuilder;\n\nsub handler {\nmy $r = Apache::Request->new(shift);\nmy $form = CGI::FormBuilder->new(... params => $r);\nprint $form->render;\n}\n\nOr, if you need to initialize a \"CGI.pm\" object separately and are using a \"post\" form\nmethod:\n\nuse CGI;\nuse CGI::FormBuilder;\n\nmy $q = new CGI;\nmy $form = CGI::FormBuilder->new(... params => $q);\n\nUsually you don't need to do this, unless you need to access other parameters outside of\nFormBuilder's control.\n\nrequired => \\@array | 'ALL' | 'NONE'\nThis is a list of those values that are required to be filled in. Those fields named must be\nincluded by the user. If the \"required\" option is not specified, by default any fields named\nin \"validate\" will be required.\n\nIn addition, the \"required\" option also takes two other settings, the strings \"ALL\" and\n\"NONE\". If you specify \"ALL\", then all fields are required. If you specify \"NONE\", then none\nof them are *in spite of what may be set via the \"validate\" option*.\n\nThis is useful if you have fields that are optional, but that you want to be validated if\nfilled in:\n\nmy $form = CGI::FormBuilder->new(\nfields => qw[/name email/],\nvalidate => { email => 'EMAIL' },\nrequired => 'NONE'\n);\n\nThis would make the \"email\" field optional, but if filled in then it would have to match the\n\"EMAIL\" pattern.\n\nIn addition, it is *very* important to note that if the \"required\" *and* \"validate\" options\nare specified, then they are taken as an intersection. That is, only those fields specified\nas \"required\" must be filled in, and the rest are optional. For example:\n\nmy $form = CGI::FormBuilder->new(\nfields => qw[/name email/],\nvalidate => { email => 'EMAIL' },\nrequired => [qw(name)]\n);\n\nThis would make the \"name\" field mandatory, but the \"email\" field optional. However, if\n\"email\" is filled in, then it must match the builtin \"EMAIL\" pattern.\n\nreset => 0 | 1 | $string\nIf set to 0, then the \"Reset\" button is not printed. If set to text, then that will be\nprinted out as the reset button. Defaults to printing out a button that says \"Reset\".\n\nselectnum => $threshold\nThis detects how FormBuilder's auto-type generation works. If a given field has options,\nthen it will be a radio group by default. However, if more than \"selectnum\" options are\npresent, then it will become a select list. The default is 5 or more options. For example:\n\n# This will be a radio group\nmy @opt = qw(Yes No);\n$form->field(name => 'answer', options => \\@opt);\n\n# However, this will be a select list\nmy @states = qw(AK CA FL NY TX);\n$form->field(name => 'state', options => \\@states);\n\n# Single items are checkboxes (allows unselect)\n$form->field(name => 'answer', options => ['Yes']);\n\nThere is no threshold for checkboxes since, if you think about it, they are really a\nmulti-radio select group. As such, a radio group becomes a checkbox group if the \"multiple\"\noption is specified and the field has *less* than \"selectnum\" options. Got it?\n\nsmartness => 0 | 1 | 2\nBy default CGI::FormBuilder tries to be pretty smart for you, like figuring out the types of\nfields based on their names and number of options. If you don't want this behavior at all,\nset \"smartness\" to 0. If you want it to be really smart, like figuring out what type of\nvalidation routines to use for you, set it to 2. It defaults to 1.\n\nsortopts => BUILTIN | 1 | \\&sub\nIf specified to \"new()\", this has the same effect as the same-named option to \"field()\",\nonly it applies to all fields.\n\nsource => $filename\nYou can use this option to initialize FormBuilder from an external configuration file. This\nallows you to separate your field code from your form layout, which is pretty cool. See\nCGI::FormBuilder::Source::File for details on the format of the external file.\n\nstatic => 0 | 1 | 2\nIf set to 1, then the form will be output with static hidden fields. If set to 2, then in\naddition fields without values will be omitted. Defaults to 0.\n\nsticky => 0 | 1\nDetermines whether or not form values should be sticky across submissions. This defaults to\n1, meaning values are sticky. However, you may want to set it to 0 if you have a form which\ndoes something like adding parts to a database. See the \"EXAMPLES\" section for a good\nexample.\n\nsubmit => 0 | 1 | $string | \\@array\nIf set to 0, then the \"Submit\" button is not printed. It defaults to creating a button that\nsays \"Submit\" verbatim. If given an argument, then that argument becomes the text to show.\nFor example:\n\nprint $form->render(submit => 'Do Lookup');\n\nWould make it so the submit button says \"Do Lookup\" on it.\n\nIf you pass an arrayref of multiple values, you get a key benefit. This will create multiple\nsubmit buttons, each with a different value. In addition, though, when submitted only the\none that was clicked will be sent across CGI via some JavaScript tricks. So this:\n\nprint $form->render(submit => ['Add A Gift', 'No Thank You']);\n\nWould create two submit buttons. Clicking on either would submit the form, but you would be\nable to see which one was submitted via the \"submitted()\" function:\n\nmy $clicked = $form->submitted;\n\nSo if the user clicked \"Add A Gift\" then that is what would end up in the variable $clicked\nabove. This allows nice conditionality:\n\nif ($form->submitted eq 'Add A Gift') {\n# show the gift selection screen\n} elsif ($form->submitted eq 'No Thank You')\n# just process the form\n}\n\nSee the \"EXAMPLES\" section for more details.\n\nstyleclass => $string\nThe string to use as the \"style\" name, if the following option is enabled.\n\nstylesheet => 0 | 1 | $path\nThis option turns on stylesheets in the HTML output by FormBuilder. Each element is printed\nwith the \"class\" of \"styleclass\" (\"fb\" by default). It is up to you to provide the actual\nstyle definitions. If you provide a $path rather than just a 1/0 toggle, then that $path\nwill be included in a \"<link>\" tag as well.\n\nThe following tags are created by this option:\n\n${styleclass}           top-level table/form class\n${styleclass}required  labels for fields that are required\n${styleclass}invalid   any fields that failed validate()\n\nIf you're contemplating stylesheets, the best thing is to just turn this option on, then see\nwhat's spit out.\n\nSee the section on \"STYLESHEETS\" for more details on FormBuilder style sheets.\n\ntable => 0 | 1 | \\%tabletags\nBy default FormBuilder decides how to layout the form based on the number of fields, values,\netc. You can force it into a table by specifying 1, or force it out of one with 0.\n\nIf you specify a hashref instead, then these will be used to create the \"<table>\" tag. For\nexample, to create a table with no cellpadding or cellspacing, use:\n\ntable => {cellpadding => 0, cellspacing => 0}\n\nAlso, you can specify options to the \"<td>\" and \"<tr>\" elements as well in the same fashion.\n\ntemplate => $filename | \\%hash | \\&sub | $object\nThis points to a filename that contains an \"HTML::Template\" compatible template to use to\nlayout the HTML. You can also specify the \"template\" option as a reference to a hash,\nallowing you to further customize the template processing options, or use other template\nengines.\n\nIf \"template\" points to a sub reference, that routine is called and its return value\ndirectly returned. If it is an object, then that object's \"render()\" routine is called and\nits value returned.\n\nFor lots more information, please see CGI::FormBuilder::Template.\n\ntext => $text\nThis is text that is included below the title but above the actual form. Useful if you want\nto say something simple like \"Contact $adm for more help\", but if you want lots of text\ncheck out the \"template\" option above.\n\ntitle => $title\nThis takes a string to use as the title of the form.\n\nvalues => \\%hash | \\@array\nThe \"values\" option takes a hashref of key/value pairs specifying the default values for the\nfields. These values will be overridden by the values entered by the user across the CGI.\nThe values are used case-insensitively, making it easier to use DBI hashref records (which\nare in upper or lower case depending on your database).\n\nThis option is useful for selecting a record from a database or hardwiring some sensible\ndefaults, and then including them in the form so that the user can change them if they wish.\nFor example:\n\nmy $rec = $sth->fetchrowhashref;\nmy $form = CGI::FormBuilder->new(fields => \\@fields,\nvalues => $rec);\n\nYou can also pass an arrayref, in which case each value is used sequentially for each field\nas specified to the \"fields\" option.\n\nvalidate => \\%hash | $object\nThis option takes either a hashref of key/value pairs or a Data::FormValidator object.\n\nIn the case of the hashref, each key is the name of a field from the \"fields\" option, or the\nstring \"ALL\" in which case it applies to all fields. Each value is one of the following:\n\n- a regular expression in 'quotes' to match against\n- an arrayref of values, of which the field must be one\n- a string that corresponds to one of the builtin patterns\n- a string containing a literal code comparison to do\n- a reference to a sub to be used to validate the field\n(the sub will receive the value to check as the first arg)\n\nIn addition, each of these can also be grouped together as:\n\n- a hashref containing pairings of comparisons to do for\nthe two different languages, \"javascript\" and \"perl\"\n\nBy default, the \"validate\" option also toggles each field to make it required. However, you\ncan use the \"required\" option to change this, see it for more details.\n\nLet's look at a concrete example. Note that the javascript validation is a negative match,\nwhile the perl validation is a positive match.\n\nmy $form = CGI::FormBuilder->new(\nfields => [qw(\nusername    password    confirmpassword\nfirstname  lastname   email\n)],\nvalidate => {\nusername   => [qw(nate jim bob)],\nfirstname => '/^\\w+$/',    # note the\nlastname  => '/^\\w+$/',    # single quotes!\nemail      => 'EMAIL',\npassword   => \\&checkpassword,\nconfirmpassword => {\njavascript => '!= form.password.value',       # neg\nperl       => 'eq $form->field(\"password\")',  # pos\n},\n},\n);\n\n# simple sub example to check the password\nsub checkpassword ($) {\nmy $v = shift;                   # first arg is value\nreturn unless $v =~ /^.{6,8}/;   # 6-8 chars\nreturn if $v eq \"password\";      # dummy check\nreturn unless passescrack($v);  # you write \"passescrack()\"\nreturn 1;                        # success\n}\n\nThis would create both JavaScript and Perl routines on the fly that would ensure:\n\n- \"username\" was either \"nate\", \"jim\", or \"bob\"\n- \"firstname\" and \"lastname\" both match the regex's specified\n- \"email\" is a valid EMAIL format\n- \"password\" passes the checks done by checkpassword(), meaning\nthat the sub returns true\n- \"confirmpassword\" is equal to the \"password\" field\n\nAny regular expressions you specify must be enclosed in single quotes because they need to\nbe used in both JavaScript and Perl code. As such, specifying a \"qr//\" will NOT work.\n\nNote that for both the \"javascript\" and \"perl\" hashref code options, the form will be\npresent as the variable named \"form\". For the Perl code, you actually get a complete $form\nobject meaning that you have full access to all its methods (although the \"field()\" method\nis probably the only one you'll need for validation).\n\nIn addition to taking any regular expression you'd like, the \"validate\" option also has many\nbuiltin defaults that can prove helpful:\n\nVALUE   -  is any type of non-null value\nWORD    -  is a word (\\w+)\nNAME    -  matches [a-zA-Z] only\nFNAME   -  person's first name, like \"Jim\" or \"Joe-Bob\"\nLNAME   -  person's last name, like \"Smith\" or \"King, Jr.\"\nNUM     -  number, decimal or integer\nINT     -  integer\nFLOAT   -  floating-point number\nPHONE   -  phone number in form \"123-456-7890\" or \"(123) 456-7890\"\nINTPHONE-  international phone number in form \"+prefix local-number\"\nEMAIL   -  email addr in form \"name@host.domain\"\nCARD    -  credit card, including Amex, with or without -'s\nDATE    -  date in format MM/DD/YYYY\nEUDATE  -  date in format DD/MM/YYYY\nMMYY    -  date in format MM/YY or MMYY\nMMYYYY  -  date in format MM/YYYY or MMYYYY\nCCMM    -  strict checking for valid credit card 2-digit month ([0-9]|1[012])\nCCYY    -  valid credit card 2-digit year\nZIPCODE -  US postal code in format 12345 or 12345-6789\nSTATE   -  valid two-letter state in all uppercase\nIPV4    -  valid IPv4 address\nNETMASK -  valid IPv4 netmask\nFILE    -  UNIX format filename (/usr/bin)\nWINFILE -  Windows format filename (C:\\windows\\system)\nMACFILE -  MacOS format filename (folder:subfolder:subfolder)\nHOST    -  valid hostname (some-name)\nDOMAIN  -  valid domainname (www.i-love-bacon.com)\nETHER   -  valid ethernet address using either : or . as separators\n\nI know some of the above are US-centric, but then again that's where I live. :-) So if you\nneed different processing just create your own regular expression and pass it in. If there's\nsomething really useful let me know and maybe I'll add it.\n\nYou can also pass a Data::FormValidator object as the value of \"validate\". This allows you\nto do things like requiring any one of several fields (but where you don't care which one).\nIn this case, the \"required\" option to \"new()\" is ignored, since you should be setting the\nrequired fields through your FormValidator profile.\n\nBy default, FormBuilder will try to use a profile named `fb' to validate itself. You can\nchange this by providing a different profile name when you call \"validate()\".\n\nNote that currently, doing validation through a FormValidator object doesn't generate any\nJavaScript validation code for you.\n\nNote that any other options specified are passed to the \"<form>\" tag verbatim. For example, you\ncould specify \"onsubmit\" or \"enctype\" to add the respective attributes.\n\nprepare()\nThis function prepares a form for rendering. It is automatically called by \"render()\", but\ncalling it yourself may be useful if you are using Catalyst or some other large framework. It\nreturns the same hash that will be used by \"render()\":\n\nmy %expanded = $form->prepare;\n\nYou could use this to, say, tweak some custom values and then pass it to your own rendering\nobject.\n\nrender()\nThis function renders the form into HTML, and returns a string containing the form. The most\ncommon use is simply:\n\nprint $form->render;\n\nYou can also supply options to \"render()\", just like you had called the accessor functions\nindividually. These two uses are equivalent:\n\n# this code:\n$form->header(1);\n$form->stylesheet('style.css');\nprint $form->render;\n\n# is the same as:\nprint $form->render(header => 1,\nstylesheet => 'style.css');\n\nNote that both forms make permanent changes to the underlying object. So the next call to\n\"render()\" will still have the header and stylesheet options in either case.\n\nfield()\nThis method is used to both get at field values:\n\nmy $bday = $form->field('birthday');\n\nAs well as make changes to their attributes:\n\n$form->field(name  => 'fname',\nlabel => \"First Name\");\n\nA very common use is to specify a list of options and/or the field type:\n\n$form->field(name    => 'state',\ntype    => 'select',\noptions => \\@states);      # you supply @states\n\nIn addition, when you call \"field()\" without any arguments, it returns a list of valid field\nnames in an array context:\n\nmy @fields = $form->field;\n\nAnd a hashref of field/value pairs in scalar context:\n\nmy $fields = $form->field;\nmy $name = $fields->{name};\n\nNote that if you call it in this manner, you only get one single value per field. This is fine\nas long as you don't have multiple values per field (the normal case). However, if you have a\nfield that allows multiple options:\n\n$form->field(name => 'color', options => \\@colors,\nmultiple => 1);        # allow multi-select\n\nThen you will only get one value for \"color\" in the hashref. In this case you'll need to access\nit via \"field()\" to get them all:\n\nmy @colors = $form->field('color');\n\nThe \"name\" option is described first, and the remaining options are in order:\n\nname => $name\nThe field to manipulate. The \"name =>\" part is optional if it's the only argument. For\nexample:\n\nmy $email = $form->field(name => 'email');\nmy $email = $form->field('email');   # same thing\n\nHowever, if you're specifying more than one argument, then you must include the \"name\" part:\n\n$form->field(name => 'email', size => '40');\n\naddafteroption => $html\nAdds the specified HTML code after each checkbox (or radio) option.\n\naddbeforeoption => $html\nAdds the specified HTML code before each checkbox (or radio) option.\n\ncolumns => 0 | $width\nIf set and the field is of type 'checkbox' or 'radio', then the options will be wrapped at\nthe given width.\n\ncomment => $string\nThis prints out the given comment *after* the field. A good use of this is for additional\nhelp on what the field should contain:\n\n$form->field(name    => 'dob',\nlabel   => 'D.O.B.',\ncomment => 'in the format MM/DD/YY');\n\nThe above would yield something like this:\n\nD.O.B. [] in the format MM/DD/YY\n\nThe comment is rendered verbatim, meaning you can use HTML links or code in it if you want.\n\ncleanopts => 0 | 1\nIf set to 1 (the default), field options are escaped to make sure any special chars don't\nscrew up the HTML. Set to 0 if you want to include verbatim HTML in your options, and know\nwhat you're doing.\n\ncookies => 0 | 1\nControls whether to generate a cookie if \"sessionid\" has been set. This also requires that\n\"header\" be set as well, since the cookie is wrapped in the header. Defaults to 1, meaning\nit will automatically work if you turn on \"header\".\n\nforce => 0 | 1\nThis is used in conjunction with the \"value\" option to forcibly override a field's value.\nSee below under the \"value\" option for more details. For compatibility with \"CGI.pm\", you\ncan also call this option \"override\" instead, but don't tell anyone.\n\ngrowable => 0 | 1 | $limit\nThis option adds a button and the appropriate JavaScript code to your form to allow the\nadditional copies of the field to be added by the client filling out the form. Currently,\nthis only works with \"text\" and \"file\" field types.\n\nIf you set \"growable\" to a positive integer greater than 1, that will become the limit of\ngrowth for that field. You won't be able to add more than $limit extra inputs to the form,\nand FormBuilder will issue a warning if the CGI params come in with more than the allowed\nnumber of values.\n\njsclick => $jscode\nThis is a cool abstraction over directly specifying the JavaScript action. This turns out to\nbe extremely useful, since if a field type changes from \"select\" to \"radio\" or \"checkbox\",\nthen the action changes from \"onchange\" to \"onclick\". Why?!?!\n\nSo if you said:\n\n$form->field(name    => 'creditcard',\noptions => \\@cards,\njsclick => 'recalctotal();');\n\nThis would generate the following code, depending on the number of @cards:\n\n<select name=\"creditcard\" onchange=\"recalctotal();\"> ...\n\n<radio name=\"creditcard\" onclick=\"recalctotal();\"> ...\n\nYou get the idea.\n\njsmessage => $string\nYou can use this to specify your own custom message for the field, which will be printed if\nit fails validation. The \"jsmessage\" option affects the JavaScript popup box, and the\n\"message\" option affects what is printed out if the server-side validation fails. If\n\"message\" is specified but not \"jsmessage\", then \"message\" will be used for JavaScript as\nwell.\n\n$form->field(name      => 'cc',\nlabel     => 'Credit Card',\nmessage   => 'Invalid credit card number',\njsmessage => 'The card number in \"%s\" is invalid');\n\nThe %s will be filled in with the field's \"label\".\n\nlabel => $string\nThis is the label printed out before the field. By default it is automatically generated\nfrom the field name. If you want to be really lazy, get in the habit of naming your database\nfields as complete words so you can pass them directly to/from your form.\n\nlabels => \\%hash\nThis option to field() is outdated. You can get the same effect by passing data structures\ndirectly to the \"options\" argument (see below). If you have well-named data, check out the\n\"nameopts\" option.\n\nThis takes a hashref of key/value pairs where each key is one of the options, and each value\nis what its printed label should be:\n\n$form->field(name    => 'state',\noptions => [qw(AZ CA NV OR WA)],\nlabels  => {\nAZ => 'Arizona',\nCA => 'California',\nNV => 'Nevada',\nOR => 'Oregon',\nWA => 'Washington\n});\n\nWhen rendered, this would create a select list where the option values were \"CA\", \"NV\", etc,\nbut where the state's full name was displayed for the user to select. As mentioned, this has\nthe exact same effect:\n\n$form->field(name    => 'state',\noptions => [\n[ AZ => 'Arizona' ],\n[ CA => 'California' ],\n[ NV => 'Nevada' ],\n[ OR => 'Oregon' ],\n[ WA => 'Washington ],\n]);\n\nI can think of some rare situations where you might have a set of predefined labels, but\nonly some of those are present in a given field... but usually you should just use the\n\"options\" arg.\n\nlinebreaks => 0 | 1\nSimilar to the top-level \"linebreaks\" option, this one will put breaks in between options,\nto space things out more. This is useful with radio and checkboxes especially.\n\nmessage => $string\nLike \"jsmessage\", this customizes the output error string if server-side validation fails\nfor the field. The \"message\" option will also be used for JavaScript messages if it is\nspecified but \"jsmessage\" is not. See above under \"jsmessage\" for details.\n\nmultiple => 0 | 1\nIf set to 1, then the user is allowed to choose multiple values from the options provided.\nThis turns radio groups into checkboxes and selects into multi-selects. Defaults to\nautomatically being figured out based on number of values.\n\nnameopts => 0 | 1\nIf set to 1, then options for select lists will be automatically named using the same\nalgorithm as field labels. For example:\n\n$form->field(name     => 'department',\noptions  => qw[(molecularbiology\nphilosophy psychology\nparticlephysics\nsocialanthropology)],\nnameopts => 1);\n\nThis would create a list like:\n\n<select name=\"department\">\n<option value=\"molecularbiology\">Molecular Biology</option>\n<option value=\"philosophy\">Philosophy</option>\n<option value=\"psychology\">Psychology</option>\n<option value=\"particlephysics\">Particle Physics</option>\n<option value=\"socialanthropology\">Social Anthropology</option>\n</select>\n\nBasically, you get names for the options that are determined in the same way as the names\nfor the fields. This is designed as a simpler alternative to using custom \"options\" data\nstructures if your data is regular enough to support it.\n\nother => 0 | 1 | \\%attr\nIf set, this automatically creates an \"other\" field to the right of the main field. This is\nvery useful if you want to present a present list, but then also allow the user to enter\ntheir own entry:\n\n$form->field(name    => 'voteforpresident',\noptions => [qw(Bush Kerry)],\nother   => 1);\n\nThat would generate HTML somewhat like this:\n\nVote For President:  [ ] Bush [ ] Kerry [ ] Other: []\n\nIf the \"other\" button is checked, then the box becomes editable so that the user can write\nin their own text. This \"other\" box will be subject to the same validation as the main\nfield, to make sure your data for that field is consistent.\n\noptions => \\@options | \\%options | \\&sub\nThis takes an arrayref of options. It also automatically results in the field becoming a\nradio (if < 5) or select list (if >= 5), unless you explicitly set the type with the \"type\"\nparameter:\n\n$form->field(name => 'opinion',\noptions => [qw(yes no maybe so)]);\n\nFrom that, you will get something like this:\n\n<select name=\"opinion\">\n<option value=\"yes\">yes</option>\n<option value=\"no\">no</option>\n<option value=\"maybe\">maybe</option>\n<option value=\"so\">so</option>\n</select>\n\nAlso, this can accept more complicated data structures, allowing you to specify different\nlabels and values for your options. If a given item is either an arrayref or hashref, then\nthe first element will be taken as the value and the second as the label. For example, this:\n\npush @opt, ['yes', 'You betcha!'];\npush @opt, ['no', 'No way Jose'];\npush @opt, ['maybe', 'Perchance...'];\npush @opt, ['so', 'So'];\n$form->field(name => 'opinion', options => \\@opt);\n\nWould result in something like the following:\n\n<select name=\"opinion\">\n<option value=\"yes\">You betcha!</option>\n<option value=\"no\">No way Jose</option>\n<option value=\"maybe\">Perchance...</option>\n<option value=\"so\">So</option>\n</select>\n\nAnd this code would have the same effect:\n\npush @opt, { yes => 'You betcha!' };\npush @opt, { no  => 'No way Jose' };\npush @opt, { maybe => 'Perchance...' };\npush @opt, { so  => 'So' };\n$form->field(name => 'opinion', options => \\@opt);\n\nFinally, you can specify a \"\\&sub\" which must return either an \"\\@arrayref\" or \"\\%hashref\"\nof data, which is then expanded using the same algorithm.\n\noptgroups => 0 | 1 | \\%hashref\nIf \"optgroups\" is specified for a field (\"select\" fields only), then the above \"options\"\narray is parsed so that the third argument is taken as the name of the optgroup, and an\n\"<optgroup>\" tag is generated appropriately.\n\nAn example will make this behavior immediately obvious:\n\nmy $opts = $dbh->selectallarrayref(\n\"select id, name, category from software\norder by category, name\"\n);\n\n$form->field(name => 'softwaretitle',\noptions => $opts,\noptgroups => 1);\n\nThe \"optgroups\" setting would then parse the third element of $opts so that you'd get an\n\"optgroup\" every time that \"category\" changed:\n\n<optgroup label=\"antivirus\">\n<option value=\"12\">Norton Anti-virus 1.2</option>\n<option value=\"11\">McAfee 1.1</option>\n</optgroup>\n<optgroup label=\"office\">\n<option value=\"3\">Microsoft Word</option>\n<option value=\"4\">Open Office</option>\n<option value=\"6\">WordPerfect</option>\n</optgroup>\n\nIn addition, if \"optgroups\" is instead a hashref, then the name of the optgroup is gotten\nfrom that. Using the above example, this would help if you had the category name in a\nseparate table, and were just storing the \"categoryid\" in the \"software\" table. You could\nprovide an \"optgroups\" hash like:\n\nmy %optgroups = (\n1   =>  'antivirus',\n2   =>  'office',\n3   =>  'misc',\n);\n$form->field(..., optgroups => \\%optgroups);\n\nNote: No attempt is made by FormBuilder to properly sort your option optgroups - it is up to\nyou to provide them in a sensible order.\n\nrequired => 0 | 1\nIf set to 1, the field must be filled in:\n\n$form->field(name => 'email', required => 1);\n\nThis is rarely useful - what you probably want are the \"validate\" and \"required\" options to\n\"new()\".\n\nselectname => 0 | 1 | $string\nBy default, this is set to 1 and any single-select lists are prefixed by the message\n\"formselectdefault\" (\"-select-\" for English). If set to 0, then this string is not\nprefixed. If set to a $string, then that string is used explicitly.\n\nPhilosophically, the \"-select-\" behavior is intentional because it allows a null item to be\ntransmitted (the same as not checking any checkboxes or radio buttons). Otherwise, the first\nitem in a select list is automatically sent when the form is submitted. If you would like an\nitem to be \"pre-selected\", consider using the \"value\" option to specify the default value.\n\nsortopts => BUILTIN | 1 | \\&sub\nIf set, and there are options, then the options will be sorted in the specified order. There\nare four possible values for the \"BUILTIN\" setting:\n\nNAME            Sort option values by name\nNUM             Sort option values numerically\nLABELNAME       Sort option labels by name\nLABELNUM        Sort option labels numerically\n\nFor example:\n\n$form->field(name => 'category',\noptions => \\@cats,\nsortopts => 'NAME');\n\nWould sort the @cats options in alphabetic (\"NAME\") order. The option \"NUM\" would sort them\nin numeric order. If you specify \"1\", then an alphabetic sort is done, just like the default\nPerl sort.\n\nIn addition, you can specify a sub reference which takes pairs of values to compare and\nreturns the appropriate return value that Perl \"sort()\" expects.\n\ntype => $type\nThe type of input box to create. Default is \"text\", and valid values include anything\nallowed by the HTML specs, including \"select\", \"radio\", \"checkbox\", \"textarea\", \"password\",\n\"hidden\", and so on.\n\nBy default, the type is automatically determined by FormBuilder based on the following\nalgorithm:\n\nField options?\nNo = text (done)\nYes:\nLess than 'selectnum' setting?\nNo = select (done)\nYes:\nIs the 'multiple' option set?\nYes = checkbox (done)\nNo:\nHave just one single option?\nYes = checkbox (done)\nNo = radio (done)\n\nI recommend you let FormBuilder do this for you in most cases, and only tweak those you\nreally need to.\n\nvalue => $value | \\@values\nThe \"value\" option can take either a single value or an arrayref of multiple values. In the\ncase of multiple values, this will result in the field automatically becoming a multiple\nselect list or radio group, depending on the number of options specified.\n\nIf a CGI value is present it will always win. To forcibly change a value, you need to\nspecify the \"force\" option:\n\n# Example that hides credit card on confirm screen\nif ($form->submitted && $form->validate) {\nmy $val = $form->field;\n\n# hide CC number\n$form->field(name => 'creditcard',\nvalue => '(not shown)',\nforce => 1);\n\nprint $form->confirm;\n}\n\nThis would print out the string \"(not shown)\" on the \"confirm()\" screen instead of the\nactual number.\n\nvalidate => '/regex/'\nSimilar to the \"validate\" option used in \"new()\", this affects the validation just of that\nsingle field. As such, rather than a hashref, you would just specify the regex to match\nagainst.\n\nThis regex must be specified as a single-quoted string, and NOT as a qr// regex. The reason\nfor this is it needs to be usable by the JavaScript routines as well.\n\n$htmlattr => $htmlval\nIn addition to the above tags, the \"field()\" function can take any other valid HTML\nattribute, which will be placed in the tag verbatim. For example, if you wanted to alter the\nclass of the field (if you're using stylesheets and a template, for example), you could say:\n\n$form->field(name => 'email', class => 'FormField',\nsize => 80);\n\nThen when you call \"$form-\"render> you would get a field something like this:\n\n<input type=\"text\" name=\"email\" class=\"FormField\" size=\"80\">\n\n(Of course, for this to really work you still have to create a class called \"FormField\" in\nyour stylesheet.)\n\nSee also the \"fieldattr\" option which provides global attributes to all fields.\n\ncgiparam()\nThe above \"field()\" method will only return fields which you have *explicitly* defined in your\nform. Excess parameters will be silently ignored, to help ensure users can't mess with your\nform.\n\nBut, you may have some times when you want extra params so that you can maintain state, but you\ndon't want it to appear in your form. Branding is an easy example:\n\nhttp://hr-outsourcing.com/newuser.cgi?company=mrpropane\n\nThis could change your page's HTML so that it displayed the appropriate company name and logo,\nwithout polluting your form parameters.\n\nThis call simply redispatches to \"CGI.pm\"'s \"param()\" method, so consult those docs for more\ninformation.\n\ntmplparam()\nThis allows you to manipulate template parameters directly. Extending the above example:\n\nmy $form = CGI::FormBuilder->new(template => 'some.tmpl');\n\nmy $company = $form->cgiparam('company');\n$form->tmplparam(company => $company);\n\nThen, in your template:\n\nHello, <tmplvar company> employee!\n<p>\nPlease fill out this form:\n<tmplvar form-start>\n<!-- etc... -->\n\nFor really precise template control, you can actually create your own template object and then\npass it directly to FormBuilder. See CGI::FormBuilder::Template for more details.\n\nsessionid()\nThis gets and sets the sessionid, which is stored in the special form field \"sessionid\". By\ndefault no session ids are generated or used. Rather, this is intended to provide a hook for you\nto easily integrate this with a session id module like \"CGI::Session\".\n\nSince you can set the session id via the \"sessionid\" field, you can pass it as an argument when\nfirst showing the form:\n\nhttp://mydomain.com/forms/updateinfo.cgi?sessionid=0123-091231\n\nThis would set things up so that if you called:\n\nmy $id = $form->sessionid;\n\nThis would get the value \"0123-091231\" in your script. Conversely, if you generate a new\nsessionid on your own, and wish to include it automatically, simply set is as follows:\n\n$form->sessionid($id);\n\nIf the sessionid is set, and \"header\" is set, then FormBuilder will also automatically generate\na cookie for you.\n\nSee \"EXAMPLES\" for \"CGI::Session\" example.\n\nsubmitted()\nThis returns the value of the \"Submit\" button if the form has been submitted, undef otherwise.\nThis allows you to either test it in a boolean context:\n\nif ($form->submitted) { ... }\n\nOr to retrieve the button that was actually clicked on in the case of multiple submit buttons:\n\nif ($form->submitted eq 'Update') {\n...\n} elsif ($form->submitted eq 'Delete') {\n...\n}\n\nIt's best to call \"validate()\" in conjunction with this to make sure the form validation works.\nTo make sure you're getting accurate info, it's recommended that you name your forms with the\n\"name\" option described above.\n\nIf you're writing a multiple-form app, you should name your forms with the \"name\" option to\nensure that you are getting an accurate return value from this sub. See the \"name\" option above,\nunder \"render()\".\n\nYou can also specify the name of an optional field which you want to \"watch\" instead of the\ndefault \"submitted\" hidden field. This is useful if you have a search form and also want to be\nable to link to it from other documents directly, such as:\n\nmysearch.cgi?lookup=what+to+look+for\n\nNormally, \"submitted()\" would return false since the \"submitted\" field is not included.\nHowever, you can override this by saying:\n\n$form->submitted('lookup');\n\nThen, if the lookup field is present, you'll get a true value. (Actually, you'll still get the\nvalue of the \"Submit\" button if present.)\n\nvalidate()\nThis validates the form based on the validation criteria passed into \"new()\" via the \"validate\"\noption. In addition, you can specify additional criteria to check that will be valid for just\nthat call of \"validate()\". This is useful is you have to deal with different geos:\n\nif ($location eq 'US') {\n$form->validate(state => 'STATE', zipcode => 'ZIPCODE');\n} else {\n$form->validate(state => '/^\\w{2,3}$/');\n}\n\nYou can also provide a Data::FormValidator object as the first argument. In that case, the\nsecond argument (if present) will be interpreted as the name of the validation profile to use. A\nsingle string argument will also be interpreted as a validation profile name.\n\nNote that if you pass args to your \"validate()\" function like this, you will not get JavaScript\ngenerated or required fields placed in bold. So, this is good for conditional validation like\nthe above example, but for most applications you want to pass your validation requirements in\nvia the \"validate\" option to the \"new()\" function, and just call the \"validate()\" function with\nno arguments.\n\nconfirm()\nThe purpose of this function is to print out a static confirmation screen showing a short\nmessage along with the values that were submitted. It is actually just a special wrapper around\n\"render()\", twiddling a couple options.\n\nIf you're using templates, you probably want to specify a separate success template, such as:\n\nif ($form->submitted && $form->validate) {\nprint $form->confirm(template => 'success.tmpl');\n} else {\nprint $form->render(template => 'fillin.tmpl');\n}\n\nSo that you don't get the same screen twice.\n\nmailconfirm()\nThis sends a confirmation email to the named addresses. The \"to\" argument is required;\neverything else is optional. If no \"from\" is specified then it will be set to the address\n\"auto-reply\" since that is a common quasi-standard in the web app world.\n\nThis does not send any of the form results. Rather, it simply prints out a message saying the\nsubmission was received.\n\nmailresults()\nThis emails the form results to the specified address(es). By default it prints out the form\nresults separated by a colon, such as:\n\nname: Nate Wiger\nemail: nate@wiger.org\ncolors: red green blue\n\nAnd so on. You can change this by specifying the \"delimiter\" and \"joiner\" options. For example\nthis:\n\n$form->mailresults(to => $to, delimiter => '=', joiner => ',');\n\nWould produce an email like this:\n\nname=Nate Wiger\nemail=nate@wiger.org\ncolors=red,green,blue\n\nNote that now the last field (\"colors\") is separated by commas since you have multiple values\nand you specified a comma as your \"joiner\".\n\nmailresults() with plugin\nNow you can also specify a plugin to use with mailresults, in the namespace\n\"CGI::FormBuilder::Mail::*\". These plugins may depend on other libraries. For example, this:\n\n$form->mailresults(\nplugin          => 'FormatMultiPart',\nfrom            => 'Mark Hedges <hedges@ucsd.edu>',\nto              => 'Nate Wiger <nwiger@gmail.com>',\nsmtp            => $smtphostorip,\nformat          => 'plain',\n);\n\nwill send your mail formatted nicely in text using \"Text::FormatTable\". (And if you used format\n=> 'html' it would use \"HTML::QuickTable\".)\n\nThis particular plugin uses \"MIME::Lite\" and \"Net::SMTP\" to communicate directly with the SMTP\nserver, and does not rely on a shell escape. See CGI::FormBuilder::Mail::FormatMultiPart for\nmore information.\n\nThis establishes a simple mail plugin implementation standard for your own mailresults()\nplugins. The plugin should reside under the \"CGI::FormBuilder::Mail::*\" namespace. It should\nhave a constructor new() which accepts a hash-as-array of named arg parameters, including form\n=> $form. It should have a mailresults() object method that does the right thing. It should use\n\"CGI::FormBuilder::Util\" and puke() if something goes wrong.\n\nCalling $form->mailresults( plugin => 'Foo', ... ) will load \"CGI::FormBuilder::Mail::Foo\" and\nwill pass the FormBuilder object as a named param 'form' with all other parameters passed\nintact.\n\nIf it should croak, confess, die or otherwise break if something goes wrong, FormBuilder.pm will\nwarn any errors and the built-in mailresults() method will still try.\n\nmail()\nThis is a more generic version of the above; it sends whatever is given as the \"text\" argument\nvia email verbatim to the \"to\" address. In addition, if you're not running \"sendmail\" you can\nspecify the \"mailer\" parameter to give the path of your mailer. This option is accepted by the\nabove functions as well.\n",
                "subsections": []
            },
            "COMPATIBILITY": {
                "content": "The following methods are provided to make FormBuilder behave more like other modules, when\ndesired.\n\nheader()\nReturns a \"CGI.pm\" header, but only if \"header => 1\" is set.\n\nparam()\nThis is an alias for \"field()\", provided for compatibility. However, while \"field()\" *does* act\n\"compliantly\" for easy use in \"CGI::Session\", \"Apache::Request\", etc, it is *not* 100% the same.\nAs such, I recommend you use \"field()\" in your code, and let receiving objects figure the\n\"param()\" thing out when needed:\n\nmy $sess = CGI::Session->new(...);\n$sess->saveparam($form);   # will see param()\n\nquerystring()\nThis returns a query string similar to \"CGI.pm\", but ONLY containing form fields and any\n\"keepextras\", if specified. Other params are ignored.\n\nselfurl()\nThis returns a self url, similar to \"CGI.pm\", but again ONLY with form fields.\n\nscriptname()\nAn alias for \"$form->action\".\n\nSTYLESHEETS (CSS)\nIf the \"stylesheet\" option is enabled (by setting it to 1 or the path of a CSS file), then\nFormBuilder will automatically output style classes for every single form element:\n\nfb              main form table\nfblabel        td containing field label\nfbfield        td containing field input tag\nfbsubmit       td containing submit button(s)\n\nfbinput        input types\nfbselect       select types\nfbcheckbox     checkbox types\nfbradio        radio types\nfboption       labels for checkbox/radio options\nfbbutton       button types\nfbhidden       hidden types\nfbstatic       static types\n\nfbrequired     span around labels for required fields\nfbinvalid      span around labels for invalid fields\nfbcomment      span around field comment\nfberror        span around field error message\n\nHere's a simple example that you can put in \"fb.css\" which spruces up a couple basic form\nfeatures:\n\n/* FormBuilder */\n.fb {\nbackground: #ffc;\nfont-family: verdana,arial,sans-serif;\nfont-size: 10pt;\n}\n\n.fblabel {\ntext-align: right;\npadding-right: 1em;\n}\n\n.fbcomment {\nfont-size: 8pt;\nfont-style: italic;\n}\n\n.fbsubmit {\ntext-align: center;\n}\n\n.fbrequired {\nfont-weight: bold;\n}\n\n.fbinvalid {\ncolor: #c00;\nfont-weight: bold;\n}\n\n.fberror {\ncolor: #c00;\nfont-style: italic;\n}\n\nOf course, if you're familiar with CSS, you know a lot more is possible. Also, you can mess with\nall the id's (if you name your forms) to manipulate fields more exactly.\n",
                "subsections": []
            },
            "EXAMPLES": {
                "content": "I find this module incredibly useful, so here are even more examples, pasted from sample code\nthat I've written:\n",
                "subsections": [
                    {
                        "name": "Ex1: order.cgi",
                        "content": "This example provides an order form, complete with validation of the important fields, and a\n\"Cancel\" button to abort the whole thing.\n\n#!/usr/bin/perl\n\nuse strict;\nuse CGI::FormBuilder;\n\nmy @states = mystatelist();   # you write this\n\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [\nqw(firstname lastname\nemail sendmeemails\naddress state zipcode\ncreditcard expiration)\n],\n\nheader => 1,\ntitle  => 'Finalize Your Order',\nsubmit => ['Place Order', 'Cancel'],\nreset  => 0,\n\nvalidate => {\nemail   => 'EMAIL',\nzipcode => 'ZIPCODE',\ncreditcard => 'CARD',\nexpiration  => 'MMYY',\n},\nrequired => 'ALL',\njsfunc => <<EOJS,\n// skip js validation if they clicked \"Cancel\"\nif (this.submit.value == 'Cancel') return true;\nEOJS\n);\n\n# Provide a list of states\n$form->field(name    => 'state',\noptions => \\@states,\nsortopts=> 'NAME');\n\n# Options for mailing list\n$form->field(name    => 'sendmeemails',\noptions => [[1 => 'Yes'], [0 => 'No']],\nvalue   => 0);   # \"No\"\n\n# Check for valid order\nif ($form->submitted eq 'Cancel') {\n# redirect them to the homepage\nprint $form->cgi->redirect('/');\nexit;\n}\nelsif ($form->submitted && $form->validate) {\n# your code goes here to do stuff...\nprint $form->confirm;\n}\nelse {\n# either first printing or needs correction\nprint $form->render;\n}\n\nThis will create a form called \"Finalize Your Order\" that will provide a pulldown menu for the\n\"state\", a radio group for \"sendmeemails\", and normal text boxes for the rest. It will then\nvalidate all the fields, using specific patterns for those fields specified to \"validate\".\n"
                    },
                    {
                        "name": "Ex2: orderform.cgi",
                        "content": "Here's an example that adds some fields dynamically, and uses the \"debug\" option spit out gook:\n\n#!/usr/bin/perl\n\nuse strict;\nuse CGI::FormBuilder;\n\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [\nqw(firstname lastname email\naddress state zipcode)\n],\nheader => 1,\ndebug  => 2,    # gook\nrequired => 'NONE',\n);\n\n# This adds on the 'details' field to our form dynamically\n$form->field(name => 'details',\ntype => 'textarea',\ncols => '50',\nrows => '10');\n\n# And this adds username with validation\n$form->field(name  => 'username',\nvalue => $ENV{REMOTEUSER},\nvalidate => 'NAME');\n\nif ($form->submitted && $form->validate) {\n# ... more code goes here to do stuff ...\nprint $form->confirm;\n} else {\nprint $form->render;\n}\n\nIn this case, none of the fields are required, but the \"username\" field will still be validated\nif filled in.\n"
                    },
                    {
                        "name": "Ex3: ticketsearch.cgi",
                        "content": "This is a simple search script that uses a template to layout the search parameters very\nprecisely. Note that we set our options for our different fields and types.\n\n#!/usr/bin/perl\n\nuse strict;\nuse CGI::FormBuilder;\n\nmy $form = CGI::FormBuilder->new(\nfields => [qw(type string status category)],\nheader => 1,\ntemplate => 'ticketsearch.tmpl',\nsubmit => 'Search',     # search button\nreset  => 0,            # and no reset\n);\n\n# Need to setup some specific field options\n$form->field(name    => 'type',\noptions => [qw(ticket requestor hostname sysadmin)]);\n\n$form->field(name    => 'status',\ntype    => 'radio',\noptions => [qw(incomplete recentlycompleted all)],\nvalue   => 'incomplete');\n\n$form->field(name    => 'category',\ntype    => 'checkbox',\noptions => [qw(server network desktop printer)]);\n\n# Render the form and print it out so our submit button says \"Search\"\nprint $form->render;\n\nThen, in our \"ticketsearch.tmpl\" HTML file, we would have something like this:\n\n<html>\n<head>\n<title>Search Engine</title>\n<tmplvar js-head>\n</head>\n<body bgcolor=\"white\">\n<center>\n<p>\nPlease enter a term to search the ticket database.\n<p>\n<tmplvar form-start>\nSearch by <tmplvar field-type> for <tmplvar field-string>\n<tmplvar form-submit>\n<p>\nStatus: <tmplvar field-status>\n<p>\nCategory: <tmplvar field-category>\n<p>\n</form>\n</body>\n</html>\n\nThat's all you need for a sticky search form with the above HTML layout. Notice that you can\nchange the HTML layout as much as you want without having to touch your CGI code.\n"
                    },
                    {
                        "name": "Ex4: userinfo.cgi",
                        "content": "This script grabs the user's information out of a database and lets them update it dynamically.\nThe DBI information is provided as an example, your mileage may vary:\n\n#!/usr/bin/perl\n\nuse strict;\nuse CGI::FormBuilder;\nuse DBI;\nuse DBD::Oracle\n\nmy $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass');\n\n# We create a new form. Note we've specified very little,\n# since we're getting all our values from our database.\nmy $form = CGI::FormBuilder->new(\nfields => [qw(username password confirmpassword\nfirstname lastname email)]\n);\n\n# Now get the value of the username from our app\nmy $user = $form->cgiparam('user');\nmy $sth = $dbh->prepare(\"select * from userinfo where user = '$user'\");\n$sth->execute;\nmy $defaulthashref = $sth->fetchrowhashref;\n\n# Render our form with the defaults we got in our hashref\nprint $form->render(values => $defaulthashref,\ntitle  => \"User information for '$user'\",\nheader => 1);\n"
                    },
                    {
                        "name": "Ex5: addpart.cgi",
                        "content": "This presents a screen for users to add parts to an inventory database. Notice how it makes use\nof the \"sticky\" option. If there's an error, then the form is presented with sticky values so\nthat the user can correct them and resubmit. If the submission is ok, though, then the form is\npresented without sticky values so that the user can enter the next part.\n\n#!/usr/bin/perl\n\nuse strict;\nuse CGI::FormBuilder;\n\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(sn pn model qty comments)],\nlabels => {\nsn => 'Serial Number',\npn => 'Part Number'\n},\nsticky => 0,\nheader => 1,\nrequired => [qw(sn pn model qty)],\nvalidate => {\nsn  => '/^[PL]\\d{2}-\\d{4}-\\d{4}$/',\npn  => '/^[AQM]\\d{2}-\\d{4}$/',\nqty => 'INT'\n},\nfont => 'arial,helvetica'\n);\n\n# shrink the qty field for prettiness, lengthen model\n$form->field(name => 'qty',   size => 4);\n$form->field(name => 'model', size => 60);\n\nif ($form->submitted) {\nif ($form->validate) {\n# Add part to database\n} else {\n# Invalid; show form and allow corrections\nprint $form->render(sticky => 1);\nexit;\n}\n}\n\n# Print form for next part addition.\nprint $form->render;\n\nWith the exception of the database code, that's the whole application.\n"
                    },
                    {
                        "name": "Ex6: Session Management",
                        "content": "This creates a session via \"CGI::Session\", and ties it in with FormBuilder:\n\n#!/usr/bin/perl\n\nuse CGI::Session;\nuse CGI::FormBuilder;\n\nmy $form = CGI::FormBuilder->new(fields => \\@fields);\n\n# Initialize session\nmy $session = CGI::Session->new('driver:File',\n$form->sessionid,\n{ Directory=>'/tmp' });\n\nif ($form->submitted && $form->validate) {\n# Automatically save all parameters\n$session->saveparam($form);\n}\n\n# Ensure we have the right sessionid (might be new)\n$form->sessionid($session->id);\n\nprint $form->render;\n\nYes, it's pretty much that easy. See CGI::FormBuilder::Multi for how to tie this into a\nmulti-page form.\n\nFREQUENTLY ASKED QUESTIONS (FAQ)\nThere are a couple questions and subtle traps that seem to poke people on a regular basis. Here\nare some hints.\n\nI'm confused. Why doesn't this work like CGI.pm?\nIf you're used to \"CGI.pm\", you have to do a little bit of a brain shift when working with this\nmodule.\n\nFormBuilder is designed to address fields as *abstract entities*. That is, you don't create a\n\"checkbox\" or \"radio group\" per se. Instead, you create a field for the data you want to\ncollect. The HTML representation is just one property of this field.\n\nSo, if you want a single-option checkbox, simply say something like this:\n\n$form->field(name    => 'joinmailinglist',\noptions => ['Yes']);\n\nIf you want it to be checked by default, you add the \"value\" arg:\n\n$form->field(name    => 'joinmailinglist',\noptions => ['Yes'],\nvalue   => 'Yes');\n\nYou see, you're creating a field that has one possible option: \"Yes\". Then, you're saying its\ncurrent value is, in fact, \"Yes\". This will result in FormBuilder creating a single-option field\n(which is a checkbox by default) and selecting the requested value (meaning that the box will be\nchecked).\n\nIf you want multiple values, then all you have to do is specify multiple options:\n\n$form->field(name    => 'joinmailinglist',\noptions => ['Yes', 'No'],\nvalue   => 'Yes');\n\nNow you'll get a radio group, and \"Yes\" will be selected for you! By viewing fields as data\nentities (instead of HTML tags) you get much more flexibility and less code maintenance. If you\nwant to be able to accept multiple values, simply use the \"multiple\" arg:\n\n$form->field(name     => 'favoritecolors',\noptions  => [qw(red green blue)],\nmultiple => 1);\n\nIn all of these examples, to get the data back you just use the \"field()\" method:\n\nmy @colors = $form->field('favoritecolors');\n\nAnd the rest is taken care of for you.\n\nHow do I make a multi-screen/multi-mode form?\nThis is easily doable, but you have to remember a couple things. Most importantly, that\nFormBuilder only knows about those fields you've told it about. So, let's assume that you're\ngoing to use a special parameter called \"mode\" to control the mode of your application so that\nyou can call it like this:\n\nmyapp.cgi?mode=list&...\nmyapp.cgi?mode=edit&...\nmyapp.cgi?mode=remove&...\n\nAnd so on. You need to do two things. First, you need the \"keepextras\" option:\n\nmy $form = CGI::FormBuilder->new(..., keepextras => 1);\n\nThis will maintain the \"mode\" field as a hidden field across requests automatically. Second, you\nneed to realize that since the \"mode\" is not a defined field, you have to get it via the\n\"cgiparam()\" method:\n\nmy $mode = $form->cgiparam('mode');\n\nThis will allow you to build a large multiscreen application easily, even integrating it with\nmodules like \"CGI::Application\" if you want.\n\nYou can also do this by simply defining \"mode\" as a field in your \"fields\" declaration. The\nreason this is discouraged is because when iterating over your fields you'll get \"mode\", which\nyou likely don't want (since it's not \"real\" data).\n\nWhy won't CGI::FormBuilder work with post requests?\nIt will, but chances are you're probably doing something like this:\n\nuse CGI qw(:standard);\nuse CGI::FormBuilder;\n\n# Our \"mode\" parameter determines what we do\nmy $mode = param('mode');\n\n# Change our form based on our mode\nif ($mode eq 'view') {\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(...)],\n);\n} elsif ($mode eq 'edit') {\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(...)],\n);\n}\n\nThe problem is this: Once you read a \"post\" request, it's gone forever. In the above code, what\nyou're doing is having \"CGI.pm\" read the \"post\" request (on the first call of \"param()\").\n\nLuckily, there is an easy solution. First, you need to modify your code to use the OO form of\n\"CGI.pm\". Then, simply specify the \"CGI\" object you create to the \"params\" option of\nFormBuilder:\n\nuse CGI;\nuse CGI::FormBuilder;\n\nmy $cgi = CGI->new;\n\n# Our \"mode\" parameter determines what we do\nmy $mode = $cgi->param('mode');\n\n# Change our form based on our mode\n# Note: since it is post, must specify the 'params' option\nif ($mode eq 'view') {\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(...)],\nparams => $cgi      # get CGI params\n);\n} elsif ($mode eq 'edit') {\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(...)],\nparams => $cgi      # get CGI params\n);\n}\n\nOr, since FormBuilder gives you a \"cgiparam()\" function, you could also modify your code so you\nuse FormBuilder exclusively, as in the previous question.\n\nHow can I change option XXX based on a conditional?\nTo change an option, simply use its accessor at any time:\n\nmy $form = CGI::FormBuilder->new(\nmethod => 'post',\nfields => [qw(name email phone)]\n);\n\nmy $mode = $form->cgiparam('mode');\n\nif ($mode eq 'add') {\n$form->title('Add a new entry');\n} elsif ($mode eq 'edit') {\n$form->title('Edit existing entry');\n\n# do something to select existing values\nmy %values = selectvalues();\n\n$form->values(\\%values);\n}\nprint $form->render;\n\nUsing the accessors makes permanent changes to your object, so be aware that if you want to\nreset something to its original value later, you'll have to first save it and then reset it:\n\nmy $style = $form->stylesheet;\n$form->stylesheet(0);       # turn off\n$form->stylesheet($style);  # original setting\n\nYou can also specify options to \"render()\", although using the accessors is the preferred way.\n\nHow do I manually override the value of a field?\nYou must specify the \"force\" option:\n\n$form->field(name  => 'nameoffield',\nvalue => $value,\nforce => 1);\n\nIf you don't specify \"force\", then the CGI value will always win. This is because of the\nstateless nature of the CGI protocol.\n\nHow do I make it so that the values aren't shown in the form?\nTurn off sticky:\n\nmy $form = CGI::FormBuilder->new(... sticky => 0);\n\nBy turning off the \"sticky\" option, you will still be able to access the values, but they won't\nshow up in the form.\n\nI can't get \"validate\" to accept my regular expressions!\nYou're probably not specifying them within single quotes. See the section on \"validate\" above.\n\nCan FormBuilder handle file uploads?\nIt sure can, and it's really easy too. Just change the \"enctype\" as an option to \"new()\":\n\nuse CGI::FormBuilder;\nmy $form = CGI::FormBuilder->new(\nenctype => 'multipart/form-data',\nmethod  => 'post',\nfields  => [qw(filename)]\n);\n\n$form->field(name => 'filename', type => 'file');\n\nAnd then get to your file the same way as \"CGI.pm\":\n\nif ($form->submitted) {\nmy $file = $form->field('filename');\n\n# save contents in file, etc ...\nopen F, \">$dir/$file\" or die $!;\nwhile (<$file>) {\nprint F;\n}\nclose F;\n\nprint $form->confirm(header => 1);\n} else {\nprint $form->render(header => 1);\n}\n\nIn fact, that's a whole file upload program right there.\n"
                    }
                ]
            },
            "REFERENCES": {
                "content": "This really doesn't belong here, but unfortunately many people are confused by references in\nPerl. Don't be - they're not that tricky. When you take a reference, you're basically turning\nsomething into a scalar value. Sort of. You have to do this if you want to pass arrays intact\ninto functions in Perl 5.\n\nA reference is taken by preceding the variable with a backslash (\\). In our examples above, you\nsaw something similar to this:\n\nmy @fields = ('name', 'email');   # same as = qw(name email)\n\nmy $form = CGI::FormBuilder->new(fields => \\@fields);\n\nHere, \"\\@fields\" is a reference. Specifically, it's an array reference, or \"arrayref\" for short.\n\nSimilarly, we can do the same thing with hashes:\n\nmy %validate = (\nname  => 'NAME';\nemail => 'EMAIL',\n);\n\nmy $form = CGI::FormBuilder->new( ... validate => \\%validate);\n\nHere, \"\\%validate\" is a hash reference, or \"hashref\".\n\nBasically, if you don't understand references and are having trouble wrapping your brain around\nthem, you can try this simple rule: Any time you're passing an array or hash into a function,\nyou must precede it with a backslash. Usually that's true for CPAN modules.\n\nFinally, there are two more types of references: anonymous arrayrefs and anonymous hashrefs.\nThese are created with \"[]\" and \"{}\", respectively. So, for our purposes there is no real\ndifference between this code:\n\nmy @fields = qw(name email);\nmy %validate = (name => 'NAME', email => 'EMAIL');\n\nmy $form = CGI::FormBuilder->new(\nfields   => \\@fields,\nvalidate => \\%validate\n);\n\nAnd this code:\n\nmy $form = CGI::FormBuilder->new(\nfields   => [ qw(name email) ],\nvalidate => { name => 'NAME', email => 'EMAIL' }\n);\n\nExcept that the latter doesn't require that we first create @fields and %validate variables.\n",
                "subsections": []
            },
            "ENVIRONMENT VARIABLES": {
                "content": "FORMBUILDERDEBUG\nThis toggles the debug flag, so that you can control FormBuilder debugging globally. Helpful in\nmodperl.\n",
                "subsections": []
            },
            "NOTES": {
                "content": "Parameters beginning with a leading underscore are reserved for future use by this module. Use\nat your own peril.\n\nThe \"field()\" method has the alias \"param()\" for compatibility with other modules, allowing you\nto pass a $form around just like a $cgi object.\n\nThe output of the HTML generated natively may change slightly from release to release. If you\nneed precise control, use a template.\n\nEvery attempt has been made to make this module taint-safe (-T). However, due to the way\ntainting works, you may run into the message \"Insecure dependency\" or \"Insecure $ENV{PATH}\". If\nso, make sure you are setting $ENV{PATH} at the top of your script.\n",
                "subsections": []
            },
            "ACKNOWLEDGEMENTS": {
                "content": "This module has really taken off, thanks to very useful input, bug reports, and encouraging\nfeedback from a number of people, including:\n\nNorton Allen\nMark Belanger\nPeter Billam\nBrad Bowman\nJonathan Buhacoff\nGodfrey Carnegie\nJakob Curdes\nLaurent Dami\nBob Egert\nPeter Eichman\nAdam Foxson\nJorge Gonzalez\nFlorian Helmberger\nMark Hedges\nMark Houliston\nVictor Igumnov\nRobert James Kaes\nDimitry Kharitonov\nRandy Kobes\nWilliam Large\nKevin Lubic\nRobert Mathews\nMehryar\nKlaas Naajikens\nKoos Pol\nShawn Poulson\nVictor Porton\nDan Collis Puro\nWolfgang Radke\nDavid Siegal\nStephan Springl\nRyan Tate\nJohn Theus\nRemi Turboult\nAndy Wardley\nRaphael Wegmann\nEmanuele Zeppieri\n\nThanks!\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "CGI::FormBuilder::Template, CGI::FormBuilder::Messages, CGI::FormBuilder::Multi,\nCGI::FormBuilder::Source::File, CGI::FormBuilder::Field, CGI::FormBuilder::Util,\nCGI::FormBuilder::Util, HTML::Template, Text::Template CGI::FastTemplate\n",
                "subsections": []
            },
            "REVISION": {
                "content": "$Id: FormBuilder.pm 65 2006-09-07 18:11:43Z nwiger $\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Copyright (c) Nate Wiger <http://nateware.com>. All Rights Reserved.\n\nThis module is free software; you may copy this under the terms of the GNU General Public\nLicense, or the Artistic License, copies of which should have accompanied your Perl kit.\n",
                "subsections": []
            }
        }
    }
}