1CGI::FormBuilder(3)   User Contributed Perl Documentation  CGI::FormBuilder(3)
2
3
4

NAME

6       CGI::FormBuilder - Easily generate and process stateful forms
7

SYNOPSIS

9           use CGI::FormBuilder;
10
11           # Assume we did a DBI query to get existing values
12           my $dbval = $sth->fetchrow_hashref;
13
14           # First create our form
15           my $form = CGI::FormBuilder->new(
16                           name     => 'acctinfo',
17                           method   => 'post',
18                           stylesheet => '/path/to/style.css',
19                           values   => $dbval,   # defaults
20                      );
21
22           # Now create form fields, in order
23           # FormBuilder will automatically determine the type for you
24           $form->field(name => 'fname', label => 'First Name');
25           $form->field(name => 'lname', label => 'Last Name');
26
27           # Setup gender field to have options
28           $form->field(name => 'gender',
29                        options => [qw(Male Female)] );
30
31           # Include validation for the email field
32           $form->field(name => 'email',
33                        size => 60,
34                        validate => 'EMAIL',
35                        required => 1);
36
37           # And the (optional) phone field
38           $form->field(name => 'phone',
39                        size => 10,
40                        validate => '/^1?-?\d{3}-?\d{3}-?\d{4}$/',
41                        comment  => '<i>optional</i>');
42
43           # Check to see if we're submitted and valid
44           if ($form->submitted && $form->validate) {
45               # Get form fields as hashref
46               my $field = $form->fields;
47
48               # Do something to update your data (you would write this)
49               do_data_update($field->{lname}, $field->{fname},
50                              $field->{email}, $field->{phone},
51                              $field->{gender});
52
53               # Show confirmation screen
54               print $form->confirm(header => 1);
55           } else {
56               # Print out the form
57               print $form->render(header => 1);
58           }
59

DESCRIPTION

61       If this is your first time using FormBuilder, you should check out the
62       website for tutorials and examples at <http://formbuilder.org>.
63
64       You should also consider joining the google group at
65       <http://groups.google.com/group/perl-formbuilder>.  There are some
66       pretty smart people on the list that can help you out.
67
68   Overview
69       I hate generating and processing forms. Hate it, hate it, hate it, hate
70       it. My forms almost always end up looking the same, and almost always
71       end up doing the same thing. Unfortunately, there haven't really been
72       any tools out there that streamline the process. Many modules simply
73       substitute Perl for HTML code:
74
75           # The manual way
76           print qq(<input name="email" type="text" size="20">);
77
78           # The module way
79           print input(-name => 'email', -type => 'text', -size => '20');
80
81       The problem is, that doesn't really gain you anything - you still have
82       just as much code. Modules like "CGI.pm" are great for decoding
83       parameters, but not for generating and processing whole forms.
84
85       The goal of CGI::FormBuilder (FormBuilder) is to provide an easy way
86       for you to generate and process entire CGI form-based applications.
87       Its main features are:
88
89       Field Abstraction
90           Viewing fields as entities (instead of just params), where the HTML
91           representation, CGI values, validation, and so on are properties of
92           each field.
93
94       DWIMmery
95           Lots of built-in "intelligence" (such as automatic field typing),
96           giving you about a 4:1 ratio of the code it generates versus what
97           you have to write.
98
99       Built-in Validation
100           Full-blown regex validation for fields, even including JavaScript
101           code generation.
102
103       Template Support
104           Pluggable support for external template engines, such as
105           "HTML::Template", "Text::Template", "Template Toolkit", and
106           "CGI::FastTemplate".
107
108       Plus, the native HTML generated is valid XHTML 1.0 Transitional.
109
110   Quick Reference
111       For the incredibly impatient, here's the quickest reference you can
112       get:
113
114           # Create form
115           my $form = CGI::FormBuilder->new(
116
117              # Important options
118              fields     => \@array | \%hash,   # define form fields
119              header     => 0 | 1,              # send Content-type?
120              method     => 'post' | 'get',     # default is get
121              name       => $string,            # namespace (recommended)
122              reset      => 0 | 1 | $str,            # "Reset" button
123              submit     => 0 | 1 | $str | \@array,  # "Submit" button(s)
124              text       => $text,              # printed above form
125              title      => $title,             # printed up top
126              required   => \@array | 'ALL' | 'NONE',  # required fields?
127              values     => \%hash | \@array,   # from DBI, session, etc
128              validate   => \%hash,             # automatic field validation
129
130              # Lesser-used options
131              action     => $script,            # not needed (loops back)
132              cookies    => 0 | 1,              # use cookies for sessionid?
133              debug      => 0 | 1 | 2 | 3,      # gunk into error_log?
134              fieldsubs  => 0 | 1,              # allow $form->$field()
135              javascript => 0 | 1 | 'auto',     # generate JS validate() code?
136              keepextras => 0 | 1 | \@array,    # keep non-field params?
137              params     => $object,            # instead of CGI.pm
138              sticky     => 0 | 1,              # keep CGI values "sticky"?
139              messages   => $file | \%hash | $locale | 'auto',
140              template   => $file | \%hash | $object,   # custom HTML
141
142              # HTML formatting and JavaScript options
143              body       => \%attr,             # {background => 'black'}
144              disabled   => 0 | 1,              # display as grayed-out?
145              fieldsets  => \@arrayref          # split form into <fieldsets>
146              font       => $font | \%attr,     # 'arial,helvetica'
147              jsfunc     => $jscode,            # JS code into validate()
148              jshead     => $jscode,            # JS code into <head>
149              linebreaks => 0 | 1,              # put breaks in form?
150              selectnum  => $threshold,         # for auto-type generation
151              smartness  => 0 | 1 | 2,          # tweak "intelligence"
152              static     => 0 | 1 | 2,          # show non-editable form?
153              styleclass => $string,            # style class to use ("fb")
154              stylesheet => 0 | 1 | $path,      # turn on style class=
155              table      => 0 | 1 | \%attr,     # wrap form in <table>?
156              td         => \%attr,             # <td> options
157              tr         => \%attr,             # <tr> options
158
159              # These are deprecated and you should use field() instead
160              fieldtype  => 'type',
161              fieldattr  => \%attr,
162              labels     => \%hash,
163              options    => \%hash,
164              sortopts   => 'NAME' | 'NUM' | 1 | \&sub,
165
166              # External source file (see CGI::FormBuilder::Source::File)
167              source     => $file,
168           );
169
170           # Tweak fields individually
171           $form->field(
172
173              # Important options
174              name       => $name,          # name of field (required)
175              label      => $string,        # shown in front of <input>
176              type       => $type,          # normally auto-determined
177              multiple   => 0 | 1,          # allow multiple values?
178              options    => \@options | \%options,   # radio/select/checkbox
179              value      => $value | \@values,       # default value
180
181              # Lesser-used options
182              fieldset   => $string,        # put field into <fieldset>
183              force      => 0 | 1,          # override CGI value?
184              growable   => 0 | 1 | $limit, # expand text/file inputs?
185              jsclick    => $jscode,        # instead of onclick
186              jsmessage  => $string,        # on JS validation failure
187              message    => $string,        # other validation failure
188              other      => 0 | 1,          # create "Other:" input?
189              required   => 0 | 1,          # must fill field in?
190              validate   => '/regex/',      # validate user input
191
192              # HTML formatting options
193              cleanopts  => 0 | 1,          # HTML-escape options?
194              columns    => 0 | $width,     # wrap field options at $width
195              comment    => $string,        # printed after field
196              disabled   => 0 | 1,          # display as grayed-out?
197              labels     => \%hash,         # deprecated (use "options")
198              linebreaks => 0 | 1,          # insert breaks in options?
199              nameopts   => 0 | 1,          # auto-name options?
200              sortopts   => 'NAME' | 'NUM' | 1 | \&sub,   # sort options?
201
202              # Change size, maxlength, or any other HTML attr
203              $htmlattr  => $htmlval,
204           );
205
206           # Check for submission
207           if ($form->submitted && $form->validate) {
208
209               # Get single value
210               my $value = $form->field('name');
211
212               # Get list of fields
213               my @field = $form->field;
214
215               # Get hashref of key/value pairs
216               my $field = $form->field;
217               my $value = $field->{name};
218
219           }
220
221           # Print form
222           print $form->render(any_opt_from_new => $some_value);
223
224       That's it. Keep reading.
225
226   Walkthrough
227       Let's walk through a whole example to see how FormBuilder works.  We'll
228       start with this, which is actually a complete (albeit simple) form
229       application:
230
231           use CGI::FormBuilder;
232
233           my @fields = qw(name email password confirm_password zipcode);
234
235           my $form = CGI::FormBuilder->new(
236                           fields => \@fields,
237                           header => 1
238                      );
239
240           print $form->render;
241
242       The above code will render an entire form, and take care of maintaining
243       state across submissions. But it doesn't really do anything useful at
244       this point.
245
246       So to start, let's add the "validate" option to make sure the data
247       entered is valid:
248
249           my $form = CGI::FormBuilder->new(
250                           fields   => \@fields,
251                           header   => 1,
252                           validate => {
253                              name  => 'NAME',
254                              email => 'EMAIL'
255                           }
256                      );
257
258       We now get a whole bunch of JavaScript validation code, and the
259       appropriate hooks are added so that the form is validated by the
260       browser "onsubmit" as well.
261
262       Now, we also want to validate our form on the server side, since the
263       user may not be running JavaScript. All we do is add the statement:
264
265           $form->validate;
266
267       Which will go through the form, checking each field specified to the
268       "validate" option to see if it's ok. If there's a problem, then that
269       field is highlighted, so that when you print it out the errors will be
270       apparent.
271
272       Of course, the above returns a truth value, which we should use to see
273       if the form was valid. That way, we only update our database if
274       everything looks good:
275
276           if ($form->validate) {
277               # print confirmation screen
278               print $form->confirm;
279           } else {
280               # print the form for them to fill out
281               print $form->render;
282           }
283
284       However, we really only want to do this after our form has been
285       submitted, since otherwise this will result in our form showing errors
286       even though the user hasn't gotten a chance to fill it out yet. As
287       such, we want to check for whether the form has been submitted() yet:
288
289           if ($form->submitted && $form->validate) {
290               # print confirmation screen
291               print $form->confirm;
292           } else {
293               # print the form for them to fill out
294               print $form->render;
295           }
296
297       Now that know that our form has been submitted and is valid, we need to
298       get our values. To do so, we use the field() method along with the name
299       of the field we want:
300
301           my $email = $form->field(name => 'email');
302
303       Note we can just specify the name of the field if it's the only option:
304
305           my $email = $form->field('email');   # same thing
306
307       As a very useful shortcut, we can get all our fields back as a hashref
308       of field/value pairs by calling field() with no arguments:
309
310           my $fields = $form->field;      # all fields as hashref
311
312       To make things easy, we'll use this form so that we can pass it easily
313       into a sub of our choosing:
314
315           if ($form->submitted && $form->validate) {
316               # form was good, let's update database
317               my $fields = $form->field;
318
319               # update database (you write this part)
320               do_data_update($fields);
321
322               # print confirmation screen
323               print $form->confirm;
324           }
325
326       Finally, let's say we decide that we like our form fields, but we need
327       the HTML to be laid out very precisely. No problem! We simply create an
328       "HTML::Template" compatible template and tell FormBuilder to use it.
329       Then, in our template, we include a couple special tags which
330       FormBuilder will automatically expand:
331
332           <html>
333           <head>
334           <title><tmpl_var form-title></title>
335           <tmpl_var js-head><!-- this holds the JavaScript code -->
336           </head>
337           <tmpl_var form-start><!-- this holds the initial form tag -->
338           <h3>User Information</h3>
339           Please fill out the following information:
340           <!-- each of these tmpl_var's corresponds to a field -->
341           <p>Your full name: <tmpl_var field-name>
342           <p>Your email address: <tmpl_var field-email>
343           <p>Choose a password: <tmpl_var field-password>
344           <p>Please confirm it: <tmpl_var field-confirm_password>
345           <p>Your home zipcode: <tmpl_var field-zipcode>
346           <p>
347           <tmpl_var form-submit><!-- this holds the form submit button -->
348           </form><!-- can also use "tmpl_var form-end", same thing -->
349
350       Then, all we need to do add the "template" option, and the rest of the
351       code stays the same:
352
353           my $form = CGI::FormBuilder->new(
354                           fields   => \@fields,
355                           header   => 1,
356                           validate => {
357                              name  => 'NAME',
358                              email => 'EMAIL'
359                           },
360                           template => 'userinfo.tmpl'
361                      );
362
363       So, our complete code thus far looks like this:
364
365           use CGI::FormBuilder;
366
367           my @fields = qw(name email password confirm_password zipcode);
368
369           my $form = CGI::FormBuilder->new(
370                           fields   => \@fields,
371                           header   => 1,
372                           validate => {
373                              name  => 'NAME',
374                              email => 'EMAIL'
375                           },
376                           template => 'userinfo.tmpl',
377                      );
378
379           if ($form->submitted && $form->validate) {
380               # form was good, let's update database
381               my $fields = $form->field;
382
383               # update database (you write this part)
384               do_data_update($fields);
385
386               # print confirmation screen
387               print $form->confirm;
388
389           } else {
390               # print the form for them to fill out
391               print $form->render;
392           }
393
394       You may be surprised to learn that for many applications, the above is
395       probably all you'll need. Just fill in the parts that affect what you
396       want to do (like the database code), and you're on your way.
397
398       Note: If you are confused at all by the backslashes you see in front of
399       some data pieces above, such as "\@fields", skip down to the brief
400       section entitled "REFERENCES" at the bottom of this document (it's
401       short).
402

METHODS

404       This documentation is very extensive, but can be a bit dizzying due to
405       the enormous number of options that let you tweak just about anything.
406       As such, I recommend that you stop and visit:
407
408           www.formbuilder.org
409
410       And click on "Tutorials" and "Examples". Then, use the following
411       section as a reference later on.
412
413   new()
414       This method creates a new $form object, which you then use to generate
415       and process your form. In the very shortest version, you can just
416       specify a list of fields for your form:
417
418           my $form = CGI::FormBuilder->new(
419                           fields => [qw(first_name birthday favorite_car)]
420                      );
421
422       As of 3.02:
423
424           my $form = CGI::FormBuilder->new(
425                           source => 'myform.conf'   # form and field options
426                      );
427
428       For details on the external file format, see
429       CGI::FormBuilder::Source::File.
430
431       Any of the options below, in addition to being specified to new(), can
432       also be manipulated directly with a method of the same name. For
433       example, to change the "header" and "stylesheet" options, either of
434       these works:
435
436           # Way 1
437           my $form = CGI::FormBuilder->new(
438                           fields => \@fields,
439                           header => 1,
440                           stylesheet => '/path/to/style.css',
441                      );
442
443           # Way 2
444           my $form = CGI::FormBuilder->new(
445                           fields => \@fields
446                      );
447           $form->header(1);
448           $form->stylesheet('/path/to/style.css');
449
450       The second form is useful if you want to wrap certain options in
451       conditionals:
452
453           if ($have_template) {
454               $form->header(0);
455               $form->template('template.tmpl');
456           } else {
457               $form->header(1);
458               $form->stylesheet('/path/to/style.css');
459           }
460
461       The following is a description of each option, in alphabetical order:
462
463       action => $script
464           What script to point the form to. Defaults to itself, which is the
465           recommended setting.
466
467       body => \%attr
468           This takes a hashref of attributes that will be stuck in the
469           "<body>" tag verbatim (for example, bgcolor, alink, etc).  See the
470           "fieldattr" tag for more details, and also the "template" option.
471
472       charset
473           This forcibly overrides the charset. Better handled by loading an
474           appropriate "messages" module, which will set this for you.  See
475           CGI::FormBuilder::Messages for more details.
476
477       debug => 0 | 1 | 2 | 3
478           If set to 1, the module spits copious debugging info to STDERR.  If
479           set to 2, it spits out even more gunk. 3 is too much. Defaults to
480           0.
481
482       fields => \@array | \%hash
483           As shown above, the "fields" option takes an arrayref of fields to
484           use in the form. The fields will be printed out in the same order
485           they are specified. This option is needed if you expect your form
486           to have any fields, and is the central option to FormBuilder.
487
488           You can also specify a hashref of key/value pairs. The advantage is
489           you can then bypass the "values" option. However, the big
490           disadvantage is you cannot control the order of the fields. This is
491           ok if you're using a template, but in real-life it turns out that
492           passing a hashref to "fields" is not very useful.
493
494       fieldtype => 'type'
495           This can be used to set the default type for all fields in the
496           form.  You can then override it on a per-field basis using the
497           field() method.
498
499       fieldattr => \%attr
500           This option allows you to specify any HTML attribute and have it be
501           the default for all fields. This used to be good for stylesheets,
502           but now that there is a "stylesheet" option, this is fairly
503           useless.
504
505       fieldsets => \@attr
506           This allows you to define fieldsets for your form. Fieldsets are
507           used to group fields together. Fields are rendered in order, inside
508           the fieldset they belong to. If a field does not have a fieldset,
509           it is appended to the end of the form.
510
511           To use fieldsets, specify an arrayref of "<fieldset>" names:
512
513               fieldsets => [qw(account preferences contacts)]
514
515           You can get a different "<legend>" tag if you specify a nested
516           arrayref:
517
518               fieldsets => [
519                   [ account  => 'Account Information' ],
520                   [ preferences => 'Website Preferences' ],
521                   [ contacts => 'Email and Phone Numbers' ],
522               ]
523
524           If you're using the source file, that looks like this:
525
526               fieldsets: account=Account Information,preferences=...
527
528           Then, for each field, specify which fieldset it belongs to:
529
530               $form->field(name => 'first_name', fieldset => 'account');
531               $form->field(name => 'last_name',  fieldset => 'account');
532               $form->field(name => 'email_me',   fieldset => 'preferences');
533               $form->field(name => 'home_phone', fieldset => 'contacts');
534               $form->field(name => 'work_phone', fieldset => 'contacts');
535
536           You can also automatically create a new "fieldset" on the fly by
537           specifying a new one:
538
539               $form->field(name => 'remember_me', fieldset => 'advanced');
540
541           To set the "<legend>" in this case, you have two options.  First,
542           you can just choose a more readable "fieldset" name:
543
544               $form->field(name => 'remember_me',
545                            fieldset => 'Advanced');
546
547           Or, you can change the name using the "fieldset" accessor:
548
549               $form->fieldset(advanced => 'Advanced Options');
550
551           Note that fieldsets without fields are silently ignored, so you can
552           also just specify a huge list of possible fieldsets to new(), and
553           then only add fields as you need them.
554
555       fieldsubs => 0 | 1
556           This allows autoloading of field names so you can directly access
557           them as:
558
559               $form->$fieldname(opt => 'val');
560
561           Instead of:
562
563               $form->field(name => $fieldname, opt => 'val');
564
565           Warning: If present, it will hide any attributes of the same name.
566           For example, if you define "name" field, you won't be able to
567           change your form's name dynamically. Also, you cannot use this
568           format to create new fields. Use with caution.
569
570       font => $font | \%attr
571           The font face to use for the form. This is output as a series of
572           "<font>" tags for old browser compatibility, and will properly nest
573           them in all of the table elements. If you specify a hashref instead
574           of just a font name, then each key/value pair will be taken as part
575           of the "<font>" tag:
576
577               font => {face => 'verdana', size => '-1', color => 'gray'}
578
579           The above becomes:
580
581               <font face="verdana" size="-1" color="gray">
582
583           I used to use this all the time, but the "stylesheet" option is SO
584           MUCH BETTER. Trust me, take a day and learn the basics of CSS, it's
585           totally worth it.
586
587       header => 0 | 1
588           If set to 1, a valid "Content-type" header will be printed out,
589           along with a whole bunch of HTML "<body>" code, a "<title>" tag,
590           and so on. This defaults to 0, since often people end up using
591           templates or embedding forms in other HTML.
592
593       javascript => 0 | 1
594           If set to 1, JavaScript is generated in addition to HTML, the
595           default setting.
596
597       jserror => 'function_name'
598           If specified, this will get called instead of the standard JS
599           alert() function on error. The function signature is:
600
601               function_name(form, invalid, alertstr, invalid_fields)
602
603           The function can be named anything you like. A simple one might
604           look like this:
605
606               my $form = CGI::FormBuilder->new(
607                   jserror => 'field_errors',
608                   jshead => <<'EOJS',
609           function field_errors(form, invalid, alertstr, invalid_fields) {
610               // first reset all fields
611               for (var i=0; i < form.elements.length; i++) {
612                   form.elements[i].className = 'normal_field';
613               }
614               // now attach a special style class to highlight the field
615               for (var i=0; i < invalid_fields.length; i++) {
616                   form.elements[invalid_fields[i]].className = 'invalid_field';
617               }
618               alert(alertstr);
619               return false;
620           }
621           EOJS
622               );
623
624           Note that it should return false to prevent form submission.
625
626           This can be used in conjunction with "jsfunc", which can add
627           additional manual validations before "jserror" is called.
628
629       jsfunc => $jscode
630           This is verbatim JavaScript that will go into the "validate"
631           JavaScript function. It is useful for adding your own validation
632           code, while still getting all the automatic hooks. If something
633           fails, you should do two things:
634
635               1. append to the JavaScript string "alertstr"
636               2. increment the JavaScript number "invalid"
637
638           For example:
639
640               my $jsfunc = <<'EOJS';   # note single quote (see Hint)
641                 if (form.password.value == 'password') {
642                   alertstr += "Moron, you can't use 'password' for your password!\\n";
643                   invalid++;
644                 }
645               EOJS
646
647               my $form = CGI::FormBuilder->new(... jsfunc => $jsfunc);
648
649           Then, this code will be automatically called when form validation
650           is invoked. I find this option can be incredibly useful. Most
651           often, I use it to bypass validation on certain submit modes. The
652           submit button that was clicked is "form._submit.value":
653
654               my $jsfunc = <<'EOJS';   # note single quotes (see Hint)
655                 if (form._submit.value == 'Delete') {
656                    if (confirm("Really DELETE this entry?")) return true;
657                    return false;
658                 } else if (form._submit.value == 'Cancel') {
659                    // skip validation since we're cancelling
660                    return true;
661                 }
662               EOJS
663
664           Hint: To prevent accidental expansion of embedding strings and
665           escapes, you should put your "HERE" string in single quotes, as
666           shown above.
667
668       jshead => $jscode
669           If using JavaScript, you can also specify some JavaScript code that
670           will be included verbatim in the <head> section of the document.
671           I'm not very fond of this one, what you probably want is the
672           previous option.
673
674       keepextras => 0 | 1 | \@array
675           If set to 1, then extra parameters not set in your fields
676           declaration will be kept as hidden fields in the form. However, you
677           will need to use cgi_param(), NOT field(), to access the values.
678
679           This is useful if you want to keep some extra parameters like mode
680           or company available but not have them be valid form fields:
681
682               keepextras => 1
683
684           That will preserve any extra params. You can also specify an
685           arrayref, in which case only params in that list will be preserved.
686           For example:
687
688               keepextras => [qw(mode company)]
689
690           Will only preserve the params "mode" and "company". Again, to
691           access them:
692
693               my $mode = $form->cgi_param('mode');
694               $form->cgi_param(name => 'mode', value => 'relogin');
695
696           See "CGI.pm" for details on param() usage.
697
698       labels => \%hash
699           Like "values", this is a list of key/value pairs where the keys are
700           the names of "fields" specified above. By default, FormBuilder does
701           some snazzy case and character conversion to create pretty labels
702           for you. However, if you want to explicitly name your fields, use
703           this option.
704
705           For example:
706
707               my $form = CGI::FormBuilder->new(
708                               fields => [qw(name email)],
709                               labels => {
710                                   name  => 'Your Full Name',
711                                   email => 'Primary Email Address'
712                               }
713                          );
714
715           Usually you'll find that if you're contemplating this option what
716           you really want is a template.
717
718       lalign => 'left' | 'right' | 'center'
719           A legacy shortcut for:
720
721               th => { align => 'left' }
722
723           Even better, use the "stylesheet" option and tweak the ".fb_label"
724           class. Either way, don't use this.
725
726       lang
727           This forcibly overrides the lang. Better handled by loading an
728           appropriate "messages" module, which will set this for you.  See
729           CGI::FormBuilder::Messages for more details.
730
731       method => 'post' | 'get'
732           The type of CGI method to use, either "post" or "get". Defaults to
733           "get" if nothing is specified. Note that for forms that cause
734           changes on the server, such as database inserts, you should use the
735           "post" method.
736
737       messages => 'auto' | $file | \%hash | $locale
738           This option overrides the default FormBuilder messages in order to
739           provide multilingual locale support (or just different text for the
740           picky ones).  For details on this option, please refer to
741           CGI::FormBuilder::Messages.
742
743       name => $string
744           This names the form. It is optional, but when used, it renames
745           several key variables and functions according to the name of the
746           form. In addition, it also adds the following "<div>" tags to each
747           row of the table:
748
749               <tr id="${form}_${field}_row">
750                   <td id="${form}_${field}_label">Label</td>
751                   <td id="${form}_${field}_input"><input tag></td>
752                   <td id="${form}_${field}_error">Error</td><!-- if invalid -->
753               </tr>
754
755           These changes allow you to (a) use multiple forms in a sequential
756           application and/or (b) display multiple forms inline in one
757           document. If you're trying to build a complex multi-form app and
758           are having problems, try naming your forms.
759
760       options => \%hash
761           This is one of several meta-options that allows you to specify
762           stuff for multiple fields at once:
763
764               my $form = CGI::FormBuilder->new(
765                               fields => [qw(part_number department in_stock)],
766                               options => {
767                                   department => [qw(hardware software)],
768                                   in_stock   => [qw(yes no)],
769                               }
770                          );
771
772           This has the same effect as using field() for the "department" and
773           "in_stock" fields to set options individually.
774
775       params => $object
776           This specifies an object from which the parameters should be
777           derived.  The object must have a param() method which will return
778           values for each parameter by name. By default a CGI object will be
779           automatically created and used.
780
781           However, you will want to specify this if you're using "mod_perl":
782
783               use Apache::Request;
784               use CGI::FormBuilder;
785
786               sub handler {
787                   my $r = Apache::Request->new(shift);
788                   my $form = CGI::FormBuilder->new(... params => $r);
789                   print $form->render;
790               }
791
792           Or, if you need to initialize a "CGI.pm" object separately and are
793           using a "post" form method:
794
795               use CGI;
796               use CGI::FormBuilder;
797
798               my $q = new CGI;
799               my $form = CGI::FormBuilder->new(... params => $q);
800
801           Usually you don't need to do this, unless you need to access other
802           parameters outside of FormBuilder's control.
803
804       required => \@array | 'ALL' | 'NONE'
805           This is a list of those values that are required to be filled in.
806           Those fields named must be included by the user. If the "required"
807           option is not specified, by default any fields named in "validate"
808           will be required.
809
810           In addition, the "required" option also takes two other settings,
811           the strings "ALL" and "NONE". If you specify "ALL", then all fields
812           are required. If you specify "NONE", then none of them are in spite
813           of what may be set via the "validate" option.
814
815           This is useful if you have fields that are optional, but that you
816           want to be validated if filled in:
817
818               my $form = CGI::FormBuilder->new(
819                               fields => qw[/name email/],
820                               validate => { email => 'EMAIL' },
821                               required => 'NONE'
822                          );
823
824           This would make the "email" field optional, but if filled in then
825           it would have to match the "EMAIL" pattern.
826
827           In addition, it is very important to note that if the "required"
828           and "validate" options are specified, then they are taken as an
829           intersection. That is, only those fields specified as "required"
830           must be filled in, and the rest are optional. For example:
831
832               my $form = CGI::FormBuilder->new(
833                               fields => qw[/name email/],
834                               validate => { email => 'EMAIL' },
835                               required => [qw(name)]
836                          );
837
838           This would make the "name" field mandatory, but the "email" field
839           optional. However, if "email" is filled in, then it must match the
840           builtin "EMAIL" pattern.
841
842       reset => 0 | 1 | $string
843           If set to 0, then the "Reset" button is not printed. If set to
844           text, then that will be printed out as the reset button. Defaults
845           to printing out a button that says "Reset".
846
847       selectnum => $threshold
848           This detects how FormBuilder's auto-type generation works. If a
849           given field has options, then it will be a radio group by default.
850           However, if more than "selectnum" options are present, then it will
851           become a select list. The default is 5 or more options. For
852           example:
853
854               # This will be a radio group
855               my @opt = qw(Yes No);
856               $form->field(name => 'answer', options => \@opt);
857
858               # However, this will be a select list
859               my @states = qw(AK CA FL NY TX);
860               $form->field(name => 'state', options => \@states);
861
862               # Single items are checkboxes (allows unselect)
863               $form->field(name => 'answer', options => ['Yes']);
864
865           There is no threshold for checkboxes since, if you think about it,
866           they are really a multi-radio select group. As such, a radio group
867           becomes a checkbox group if the "multiple" option is specified and
868           the field has less than "selectnum" options. Got it?
869
870       smartness => 0 | 1 | 2
871           By default CGI::FormBuilder tries to be pretty smart for you, like
872           figuring out the types of fields based on their names and number of
873           options. If you don't want this behavior at all, set "smartness" to
874           0. If you want it to be really smart, like figuring out what type
875           of validation routines to use for you, set it to 2. It defaults to
876           1.
877
878       sortopts => BUILTIN | 1 | \&sub
879           If specified to new(), this has the same effect as the same-named
880           option to field(), only it applies to all fields.
881
882       source => $filename
883           You can use this option to initialize FormBuilder from an external
884           configuration file. This allows you to separate your field code
885           from your form layout, which is pretty cool. See
886           CGI::FormBuilder::Source::File for details on the format of the
887           external file.
888
889       static => 0 | 1 | 2
890           If set to 1, then the form will be output with static hidden
891           fields.  If set to 2, then in addition fields without values will
892           be omitted.  Defaults to 0.
893
894       sticky => 0 | 1
895           Determines whether or not form values should be sticky across
896           submissions. This defaults to 1, meaning values are sticky.
897           However, you may want to set it to 0 if you have a form which does
898           something like adding parts to a database. See the "EXAMPLES"
899           section for a good example.
900
901       submit => 0 | 1 | $string | \@array
902           If set to 0, then the "Submit" button is not printed. It defaults
903           to creating a button that says "Submit" verbatim. If given an
904           argument, then that argument becomes the text to show. For example:
905
906               print $form->render(submit => 'Do Lookup');
907
908           Would make it so the submit button says "Do Lookup" on it.
909
910           If you pass an arrayref of multiple values, you get a key benefit.
911           This will create multiple submit buttons, each with a different
912           value.  In addition, though, when submitted only the one that was
913           clicked will be sent across CGI via some JavaScript tricks. So
914           this:
915
916               print $form->render(submit => ['Add A Gift', 'No Thank You']);
917
918           Would create two submit buttons. Clicking on either would submit
919           the form, but you would be able to see which one was submitted via
920           the submitted() function:
921
922               my $clicked = $form->submitted;
923
924           So if the user clicked "Add A Gift" then that is what would end up
925           in the variable $clicked above. This allows nice conditionality:
926
927               if ($form->submitted eq 'Add A Gift') {
928                   # show the gift selection screen
929               } elsif ($form->submitted eq 'No Thank You')
930                   # just process the form
931               }
932
933           See the "EXAMPLES" section for more details.
934
935       styleclass => $string
936           The string to use as the "style" name, if the following option is
937           enabled.
938
939       stylesheet => 0 | 1 | $path
940           This option turns on stylesheets in the HTML output by FormBuilder.
941           Each element is printed with the "class" of "styleclass" ("fb" by
942           default). It is up to you to provide the actual style definitions.
943           If you provide a $path rather than just a 1/0 toggle, then that
944           $path will be included in a "<link>" tag as well.
945
946           The following tags are created by this option:
947
948               ${styleclass}           top-level table/form class
949               ${styleclass}_required  labels for fields that are required
950               ${styleclass}_invalid   any fields that failed validate()
951
952           If you're contemplating stylesheets, the best thing is to just turn
953           this option on, then see what's spit out.
954
955           See the section on "STYLESHEETS" for more details on FormBuilder
956           style sheets.
957
958       table => 0 | 1 | \%tabletags
959           By default FormBuilder decides how to layout the form based on the
960           number of fields, values, etc. You can force it into a table by
961           specifying 1, or force it out of one with 0.
962
963           If you specify a hashref instead, then these will be used to create
964           the "<table>" tag. For example, to create a table with no
965           cellpadding or cellspacing, use:
966
967               table => {cellpadding => 0, cellspacing => 0}
968
969           Also, you can specify options to the "<td>" and "<tr>" elements as
970           well in the same fashion.
971
972       template => $filename | \%hash | \&sub | $object
973           This points to a filename that contains an "HTML::Template"
974           compatible template to use to layout the HTML. You can also specify
975           the "template" option as a reference to a hash, allowing you to
976           further customize the template processing options, or use other
977           template engines.
978
979           If "template" points to a sub reference, that routine is called and
980           its return value directly returned. If it is an object, then that
981           object's render() routine is called and its value returned.
982
983           For lots more information, please see CGI::FormBuilder::Template.
984
985       text => $text
986           This is text that is included below the title but above the actual
987           form. Useful if you want to say something simple like "Contact $adm
988           for more help", but if you want lots of text check out the
989           "template" option above.
990
991       title => $title
992           This takes a string to use as the title of the form.
993
994       values => \%hash | \@array
995           The "values" option takes a hashref of key/value pairs specifying
996           the default values for the fields. These values will be overridden
997           by the values entered by the user across the CGI. The values are
998           used case-insensitively, making it easier to use DBI hashref
999           records (which are in upper or lower case depending on your
1000           database).
1001
1002           This option is useful for selecting a record from a database or
1003           hardwiring some sensible defaults, and then including them in the
1004           form so that the user can change them if they wish. For example:
1005
1006               my $rec = $sth->fetchrow_hashref;
1007               my $form = CGI::FormBuilder->new(fields => \@fields,
1008                                                values => $rec);
1009
1010           You can also pass an arrayref, in which case each value is used
1011           sequentially for each field as specified to the "fields" option.
1012
1013       validate => \%hash | $object
1014           This option takes either a hashref of key/value pairs or a
1015           Data::FormValidator object.
1016
1017           In the case of the hashref, each key is the name of a field from
1018           the "fields" option, or the string "ALL" in which case it applies
1019           to all fields. Each value is one of the following:
1020
1021               - a regular expression in 'quotes' to match against
1022               - an arrayref of values, of which the field must be one
1023               - a string that corresponds to one of the builtin patterns
1024               - a string containing a literal code comparison to do
1025               - a reference to a sub to be used to validate the field
1026                 (the sub will receive the value to check as the first arg)
1027
1028           In addition, each of these can also be grouped together as:
1029
1030               - a hashref containing pairings of comparisons to do for
1031                 the two different languages, "javascript" and "perl"
1032
1033           By default, the "validate" option also toggles each field to make
1034           it required. However, you can use the "required" option to change
1035           this, see it for more details.
1036
1037           Let's look at a concrete example.  Note that the javascript
1038           validation is a negative match, while the perl validation is a
1039           positive match.
1040
1041               my $form = CGI::FormBuilder->new(
1042                   fields => [qw(
1043                       username    password    confirm_password
1044                       first_name  last_name   email
1045                   )],
1046                   validate => {
1047                       username   => [qw(nate jim bob)],
1048                       first_name => '/^\w+$/',    # note the
1049                       last_name  => '/^\w+$/',    # single quotes!
1050                       email      => 'EMAIL',
1051                       password   => \&check_password,
1052                       confirm_password => {
1053                           javascript => '!= form.password.value',       # neg
1054                           perl       => 'eq $form->field("password")',  # pos
1055                       },
1056                   },
1057               );
1058
1059               # simple sub example to check the password
1060               sub check_password ($) {
1061                   my $v = shift;                   # first arg is value
1062                   return unless $v =~ /^.{6,8}/;   # 6-8 chars
1063                   return if $v eq "password";      # dummy check
1064                   return unless passes_crack($v);  # you write "passes_crack()"
1065                   return 1;                        # success
1066               }
1067
1068           This would create both JavaScript and Perl routines on the fly that
1069           would ensure:
1070
1071               - "username" was either "nate", "jim", or "bob"
1072               - "first_name" and "last_name" both match the regex's specified
1073               - "email" is a valid EMAIL format
1074               - "password" passes the checks done by check_password(), meaning
1075                  that the sub returns true
1076               - "confirm_password" is equal to the "password" field
1077
1078           Any regular expressions you specify must be enclosed in single
1079           quotes because they need to be used in both JavaScript and Perl
1080           code. As such, specifying a "qr//" will NOT work.
1081
1082           Note that for both the "javascript" and "perl" hashref code
1083           options, the form will be present as the variable named "form". For
1084           the Perl code, you actually get a complete $form object meaning
1085           that you have full access to all its methods (although the field()
1086           method is probably the only one you'll need for validation).
1087
1088           In addition to taking any regular expression you'd like, the
1089           "validate" option also has many builtin defaults that can prove
1090           helpful:
1091
1092               VALUE   -  is any type of non-null value
1093               WORD    -  is a word (\w+)
1094               NAME    -  matches [a-zA-Z] only
1095               FNAME   -  person's first name, like "Jim" or "Joe-Bob"
1096               LNAME   -  person's last name, like "Smith" or "King, Jr."
1097               NUM     -  number, decimal or integer
1098               INT     -  integer
1099               FLOAT   -  floating-point number
1100               PHONE   -  phone number in form "123-456-7890" or "(123) 456-7890"
1101               INTPHONE-  international phone number in form "+prefix local-number"
1102               EMAIL   -  email addr in form "name@host.domain"
1103               CARD    -  credit card, including Amex, with or without -'s
1104               DATE    -  date in format MM/DD/YYYY
1105               EUDATE  -  date in format DD/MM/YYYY
1106               MMYY    -  date in format MM/YY or MMYY
1107               MMYYYY  -  date in format MM/YYYY or MMYYYY
1108               CCMM    -  strict checking for valid credit card 2-digit month ([0-9]|1[012])
1109               CCYY    -  valid credit card 2-digit year
1110               ZIPCODE -  US postal code in format 12345 or 12345-6789
1111               STATE   -  valid two-letter state in all uppercase
1112               IPV4    -  valid IPv4 address
1113               NETMASK -  valid IPv4 netmask
1114               FILE    -  UNIX format filename (/usr/bin)
1115               WINFILE -  Windows format filename (C:\windows\system)
1116               MACFILE -  MacOS format filename (folder:subfolder:subfolder)
1117               HOST    -  valid hostname (some-name)
1118               DOMAIN  -  valid domainname (www.i-love-bacon.com)
1119               ETHER   -  valid ethernet address using either : or . as separators
1120
1121           I know some of the above are US-centric, but then again that's
1122           where I live. :-) So if you need different processing just create
1123           your own regular expression and pass it in. If there's something
1124           really useful let me know and maybe I'll add it.
1125
1126           You can also pass a Data::FormValidator object as the value of
1127           "validate".  This allows you to do things like requiring any one of
1128           several fields (but where you don't care which one). In this case,
1129           the "required" option to new() is ignored, since you should be
1130           setting the required fields through your FormValidator profile.
1131
1132           By default, FormBuilder will try to use a profile named `fb' to
1133           validate itself. You can change this by providing a different
1134           profile name when you call validate().
1135
1136           Note that currently, doing validation through a FormValidator
1137           object doesn't generate any JavaScript validation code for you.
1138
1139       Note that any other options specified are passed to the "<form>" tag
1140       verbatim. For example, you could specify "onsubmit" or "enctype" to add
1141       the respective attributes.
1142
1143   prepare()
1144       This function prepares a form for rendering. It is automatically called
1145       by render(), but calling it yourself may be useful if you are using
1146       Catalyst or some other large framework. It returns the same hash that
1147       will be used by render():
1148
1149           my %expanded = $form->prepare;
1150
1151       You could use this to, say, tweak some custom values and then pass it
1152       to your own rendering object.
1153
1154   render()
1155       This function renders the form into HTML, and returns a string
1156       containing the form. The most common use is simply:
1157
1158           print $form->render;
1159
1160       You can also supply options to render(), just like you had called the
1161       accessor functions individually. These two uses are equivalent:
1162
1163           # this code:
1164           $form->header(1);
1165           $form->stylesheet('style.css');
1166           print $form->render;
1167
1168           # is the same as:
1169           print $form->render(header => 1,
1170                               stylesheet => 'style.css');
1171
1172       Note that both forms make permanent changes to the underlying object.
1173       So the next call to render() will still have the header and stylesheet
1174       options in either case.
1175
1176   field()
1177       This method is used to both get at field values:
1178
1179           my $bday = $form->field('birthday');
1180
1181       As well as make changes to their attributes:
1182
1183           $form->field(name  => 'fname',
1184                        label => "First Name");
1185
1186       A very common use is to specify a list of options and/or the field
1187       type:
1188
1189           $form->field(name    => 'state',
1190                        type    => 'select',
1191                        options => \@states);      # you supply @states
1192
1193       In addition, when you call field() without any arguments, it returns a
1194       list of valid field names in an array context:
1195
1196           my @fields = $form->field;
1197
1198       And a hashref of field/value pairs in scalar context:
1199
1200           my $fields = $form->field;
1201           my $name = $fields->{name};
1202
1203       Note that if you call it in this manner, you only get one single value
1204       per field. This is fine as long as you don't have multiple values per
1205       field (the normal case). However, if you have a field that allows
1206       multiple options:
1207
1208           $form->field(name => 'color', options => \@colors,
1209                        multiple => 1);        # allow multi-select
1210
1211       Then you will only get one value for "color" in the hashref. In this
1212       case you'll need to access it via field() to get them all:
1213
1214           my @colors = $form->field('color');
1215
1216       The "name" option is described first, and the remaining options are in
1217       order:
1218
1219       name => $name
1220           The field to manipulate. The "name =>" part is optional if it's the
1221           only argument. For example:
1222
1223               my $email = $form->field(name => 'email');
1224               my $email = $form->field('email');   # same thing
1225
1226           However, if you're specifying more than one argument, then you must
1227           include the "name" part:
1228
1229               $form->field(name => 'email', size => '40');
1230
1231       add_after_option => $html
1232           Adds the specified HTML code after each checkbox (or radio) option.
1233
1234       add_before_option => $html
1235           Adds the specified HTML code before each checkbox (or radio)
1236           option.
1237
1238       columns => 0 | $width
1239           If set and the field is of type 'checkbox' or 'radio', then the
1240           options will be wrapped at the given width.
1241
1242       comment => $string
1243           This prints out the given comment after the field. A good use of
1244           this is for additional help on what the field should contain:
1245
1246               $form->field(name    => 'dob',
1247                            label   => 'D.O.B.',
1248                            comment => 'in the format MM/DD/YY');
1249
1250           The above would yield something like this:
1251
1252               D.O.B. [____________] in the format MM/DD/YY
1253
1254           The comment is rendered verbatim, meaning you can use HTML links or
1255           code in it if you want.
1256
1257       cleanopts => 0 | 1
1258           If set to 1 (the default), field options are escaped to make sure
1259           any special chars don't screw up the HTML. Set to 0 if you want to
1260           include verbatim HTML in your options, and know what you're doing.
1261
1262       cookies => 0 | 1
1263           Controls whether to generate a cookie if "sessionid" has been set.
1264           This also requires that "header" be set as well, since the cookie
1265           is wrapped in the header. Defaults to 1, meaning it will
1266           automatically work if you turn on "header".
1267
1268       force => 0 | 1
1269           This is used in conjunction with the "value" option to forcibly
1270           override a field's value. See below under the "value" option for
1271           more details. For compatibility with "CGI.pm", you can also call
1272           this option "override" instead, but don't tell anyone.
1273
1274       growable => 0 | 1 | $limit
1275           This option adds a button and the appropriate JavaScript code to
1276           your form to allow the additional copies of the field to be added
1277           by the client filling out the form. Currently, this only works with
1278           "text" and "file" field types.
1279
1280           If you set "growable" to a positive integer greater than 1, that
1281           will become the limit of growth for that field. You won't be able
1282           to add more than $limit extra inputs to the form, and FormBuilder
1283           will issue a warning if the CGI params come in with more than the
1284           allowed number of values.
1285
1286       jsclick => $jscode
1287           This is a cool abstraction over directly specifying the JavaScript
1288           action. This turns out to be extremely useful, since if a field
1289           type changes from "select" to "radio" or "checkbox", then the
1290           action changes from "onchange" to "onclick". Why?!?!
1291
1292           So if you said:
1293
1294               $form->field(name    => 'credit_card',
1295                            options => \@cards,
1296                            jsclick => 'recalc_total();');
1297
1298           This would generate the following code, depending on the number of
1299           @cards:
1300
1301               <select name="credit_card" onchange="recalc_total();"> ...
1302
1303               <radio name="credit_card" onclick="recalc_total();"> ...
1304
1305           You get the idea.
1306
1307       jsmessage => $string
1308           You can use this to specify your own custom message for the field,
1309           which will be printed if it fails validation. The "jsmessage"
1310           option affects the JavaScript popup box, and the "message" option
1311           affects what is printed out if the server-side validation fails.
1312           If "message" is specified but not "jsmessage", then "message" will
1313           be used for JavaScript as well.
1314
1315               $form->field(name      => 'cc',
1316                            label     => 'Credit Card',
1317                            message   => 'Invalid credit card number',
1318                            jsmessage => 'The card number in "%s" is invalid');
1319
1320           The %s will be filled in with the field's "label".
1321
1322       label => $string
1323           This is the label printed out before the field. By default it is
1324           automatically generated from the field name. If you want to be
1325           really lazy, get in the habit of naming your database fields as
1326           complete words so you can pass them directly to/from your form.
1327
1328       labels => \%hash
1329           This option to field() is outdated. You can get the same effect by
1330           passing data structures directly to the "options" argument (see
1331           below).  If you have well-named data, check out the "nameopts"
1332           option.
1333
1334           This takes a hashref of key/value pairs where each key is one of
1335           the options, and each value is what its printed label should be:
1336
1337               $form->field(name    => 'state',
1338                            options => [qw(AZ CA NV OR WA)],
1339                            labels  => {
1340                                 AZ => 'Arizona',
1341                                 CA => 'California',
1342                                 NV => 'Nevada',
1343                                 OR => 'Oregon',
1344                                 WA => 'Washington
1345                            });
1346
1347           When rendered, this would create a select list where the option
1348           values were "CA", "NV", etc, but where the state's full name was
1349           displayed for the user to select. As mentioned, this has the exact
1350           same effect:
1351
1352               $form->field(name    => 'state',
1353                            options => [
1354                               [ AZ => 'Arizona' ],
1355                               [ CA => 'California' ],
1356                               [ NV => 'Nevada' ],
1357                               [ OR => 'Oregon' ],
1358                               [ WA => 'Washington ],
1359                            ]);
1360
1361           I can think of some rare situations where you might have a set of
1362           predefined labels, but only some of those are present in a given
1363           field... but usually you should just use the "options" arg.
1364
1365       linebreaks => 0 | 1
1366           Similar to the top-level "linebreaks" option, this one will put
1367           breaks in between options, to space things out more. This is useful
1368           with radio and checkboxes especially.
1369
1370       message => $string
1371           Like "jsmessage", this customizes the output error string if
1372           server-side validation fails for the field. The "message" option
1373           will also be used for JavaScript messages if it is specified but
1374           "jsmessage" is not. See above under "jsmessage" for details.
1375
1376       multiple => 0 | 1
1377           If set to 1, then the user is allowed to choose multiple values
1378           from the options provided. This turns radio groups into checkboxes
1379           and selects into multi-selects. Defaults to automatically being
1380           figured out based on number of values.
1381
1382       nameopts => 0 | 1
1383           If set to 1, then options for select lists will be automatically
1384           named using the same algorithm as field labels. For example:
1385
1386               $form->field(name     => 'department',
1387                            options  => qw[(molecular_biology
1388                                            philosophy psychology
1389                                            particle_physics
1390                                            social_anthropology)],
1391                            nameopts => 1);
1392
1393           This would create a list like:
1394
1395               <select name="department">
1396               <option value="molecular_biology">Molecular Biology</option>
1397               <option value="philosophy">Philosophy</option>
1398               <option value="psychology">Psychology</option>
1399               <option value="particle_physics">Particle Physics</option>
1400               <option value="social_anthropology">Social Anthropology</option>
1401               </select>
1402
1403           Basically, you get names for the options that are determined in the
1404           same way as the names for the fields. This is designed as a simpler
1405           alternative to using custom "options" data structures if your data
1406           is regular enough to support it.
1407
1408       other => 0 | 1 | \%attr
1409           If set, this automatically creates an "other" field to the right of
1410           the main field. This is very useful if you want to present a
1411           present list, but then also allow the user to enter their own
1412           entry:
1413
1414               $form->field(name    => 'vote_for_president',
1415                            options => [qw(Bush Kerry)],
1416                            other   => 1);
1417
1418           That would generate HTML somewhat like this:
1419
1420               Vote For President:  [ ] Bush [ ] Kerry [ ] Other: [______]
1421
1422           If the "other" button is checked, then the box becomes editable so
1423           that the user can write in their own text. This "other" box will be
1424           subject to the same validation as the main field, to make sure your
1425           data for that field is consistent.
1426
1427       options => \@options | \%options | \&sub
1428           This takes an arrayref of options. It also automatically results in
1429           the field becoming a radio (if < 5) or select list (if >= 5),
1430           unless you explicitly set the type with the "type" parameter:
1431
1432               $form->field(name => 'opinion',
1433                            options => [qw(yes no maybe so)]);
1434
1435           From that, you will get something like this:
1436
1437               <select name="opinion">
1438               <option value="yes">yes</option>
1439               <option value="no">no</option>
1440               <option value="maybe">maybe</option>
1441               <option value="so">so</option>
1442               </select>
1443
1444           Also, this can accept more complicated data structures, allowing
1445           you to specify different labels and values for your options. If a
1446           given item is either an arrayref or hashref, then the first element
1447           will be taken as the value and the second as the label. For
1448           example, this:
1449
1450               push @opt, ['yes', 'You betcha!'];
1451               push @opt, ['no', 'No way Jose'];
1452               push @opt, ['maybe', 'Perchance...'];
1453               push @opt, ['so', 'So'];
1454               $form->field(name => 'opinion', options => \@opt);
1455
1456           Would result in something like the following:
1457
1458               <select name="opinion">
1459               <option value="yes">You betcha!</option>
1460               <option value="no">No way Jose</option>
1461               <option value="maybe">Perchance...</option>
1462               <option value="so">So</option>
1463               </select>
1464
1465           And this code would have the same effect:
1466
1467               push @opt, { yes => 'You betcha!' };
1468               push @opt, { no  => 'No way Jose' };
1469               push @opt, { maybe => 'Perchance...' };
1470               push @opt, { so  => 'So' };
1471               $form->field(name => 'opinion', options => \@opt);
1472
1473           Finally, you can specify a "\&sub" which must return either an
1474           "\@arrayref" or "\%hashref" of data, which is then expanded using
1475           the same algorithm.
1476
1477       optgroups => 0 | 1 | \%hashref
1478           If "optgroups" is specified for a field ("select" fields only),
1479           then the above "options" array is parsed so that the third argument
1480           is taken as the name of the optgroup, and an "<optgroup>" tag is
1481           generated appropriately.
1482
1483           An example will make this behavior immediately obvious:
1484
1485             my $opts = $dbh->selectall_arrayref(
1486                           "select id, name, category from software
1487                            order by category, name"
1488                         );
1489
1490             $form->field(name => 'software_title',
1491                          options => $opts,
1492                          optgroups => 1);
1493
1494           The "optgroups" setting would then parse the third element of $opts
1495           so that you'd get an "optgroup" every time that "category" changed:
1496
1497             <optgroup label="antivirus">
1498                <option value="12">Norton Anti-virus 1.2</option>
1499                <option value="11">McAfee 1.1</option>
1500             </optgroup>
1501             <optgroup label="office">
1502                <option value="3">Microsoft Word</option>
1503                <option value="4">Open Office</option>
1504                <option value="6">WordPerfect</option>
1505             </optgroup>
1506
1507           In addition, if "optgroups" is instead a hashref, then the name of
1508           the optgroup is gotten from that. Using the above example, this
1509           would help if you had the category name in a separate table, and
1510           were just storing the "category_id" in the "software" table.  You
1511           could provide an "optgroups" hash like:
1512
1513               my %optgroups = (
1514                   1   =>  'antivirus',
1515                   2   =>  'office',
1516                   3   =>  'misc',
1517               );
1518               $form->field(..., optgroups => \%optgroups);
1519
1520           Note: No attempt is made by FormBuilder to properly sort your
1521           option optgroups - it is up to you to provide them in a sensible
1522           order.
1523
1524       required => 0 | 1
1525           If set to 1, the field must be filled in:
1526
1527               $form->field(name => 'email', required => 1);
1528
1529           This is rarely useful - what you probably want are the "validate"
1530           and "required" options to new().
1531
1532       selectname => 0 | 1 | $string
1533           By default, this is set to 1 and any single-select lists are
1534           prefixed by the message "form_select_default" ("-select-" for
1535           English). If set to 0, then this string is not prefixed.  If set to
1536           a $string, then that string is used explicitly.
1537
1538           Philosophically, the "-select-" behavior is intentional because it
1539           allows a null item to be transmitted (the same as not checking any
1540           checkboxes or radio buttons). Otherwise, the first item in a select
1541           list is automatically sent when the form is submitted.  If you
1542           would like an item to be "pre-selected", consider using the "value"
1543           option to specify the default value.
1544
1545       sortopts => BUILTIN | 1 | \&sub
1546           If set, and there are options, then the options will be sorted in
1547           the specified order. There are four possible values for the
1548           "BUILTIN" setting:
1549
1550               NAME            Sort option values by name
1551               NUM             Sort option values numerically
1552               LABELNAME       Sort option labels by name
1553               LABELNUM        Sort option labels numerically
1554
1555           For example:
1556
1557               $form->field(name => 'category',
1558                            options => \@cats,
1559                            sortopts => 'NAME');
1560
1561           Would sort the @cats options in alphabetic ("NAME") order.  The
1562           option "NUM" would sort them in numeric order. If you specify "1",
1563           then an alphabetic sort is done, just like the default Perl sort.
1564
1565           In addition, you can specify a sub reference which takes pairs of
1566           values to compare and returns the appropriate return value that
1567           Perl sort() expects.
1568
1569       type => $type
1570           The type of input box to create. Default is "text", and valid
1571           values include anything allowed by the HTML specs, including
1572           "select", "radio", "checkbox", "textarea", "password", "hidden",
1573           and so on.
1574
1575           By default, the type is automatically determined by FormBuilder
1576           based on the following algorithm:
1577
1578               Field options?
1579                   No = text (done)
1580                   Yes:
1581                       Less than 'selectnum' setting?
1582                           No = select (done)
1583                           Yes:
1584                               Is the 'multiple' option set?
1585                               Yes = checkbox (done)
1586                               No:
1587                                   Have just one single option?
1588                                       Yes = checkbox (done)
1589                                       No = radio (done)
1590
1591           I recommend you let FormBuilder do this for you in most cases, and
1592           only tweak those you really need to.
1593
1594       value => $value | \@values
1595           The "value" option can take either a single value or an arrayref of
1596           multiple values. In the case of multiple values, this will result
1597           in the field automatically becoming a multiple select list or radio
1598           group, depending on the number of options specified.
1599
1600           If a CGI value is present it will always win. To forcibly change a
1601           value, you need to specify the "force" option:
1602
1603               # Example that hides credit card on confirm screen
1604               if ($form->submitted && $form->validate) {
1605                   my $val = $form->field;
1606
1607                   # hide CC number
1608                   $form->field(name => 'credit_card',
1609                                value => '(not shown)',
1610                                force => 1);
1611
1612                   print $form->confirm;
1613               }
1614
1615           This would print out the string "(not shown)" on the confirm()
1616           screen instead of the actual number.
1617
1618       validate => '/regex/'
1619           Similar to the "validate" option used in new(), this affects the
1620           validation just of that single field. As such, rather than a
1621           hashref, you would just specify the regex to match against.
1622
1623           This regex must be specified as a single-quoted string, and NOT as
1624           a qr// regex. The reason for this is it needs to be usable by the
1625           JavaScript routines as well.
1626
1627       $htmlattr => $htmlval
1628           In addition to the above tags, the field() function can take any
1629           other valid HTML attribute, which will be placed in the tag
1630           verbatim. For example, if you wanted to alter the class of the
1631           field (if you're using stylesheets and a template, for example),
1632           you could say:
1633
1634               $form->field(name => 'email', class => 'FormField',
1635                            size => 80);
1636
1637           Then when you call "$form-"render> you would get a field something
1638           like this:
1639
1640               <input type="text" name="email" class="FormField" size="80">
1641
1642           (Of course, for this to really work you still have to create a
1643           class called "FormField" in your stylesheet.)
1644
1645           See also the "fieldattr" option which provides global attributes to
1646           all fields.
1647
1648   cgi_param()
1649       The above field() method will only return fields which you have
1650       explicitly defined in your form. Excess parameters will be silently
1651       ignored, to help ensure users can't mess with your form.
1652
1653       But, you may have some times when you want extra params so that you can
1654       maintain state, but you don't want it to appear in your form. Branding
1655       is an easy example:
1656
1657           http://hr-outsourcing.com/newuser.cgi?company=mr_propane
1658
1659       This could change your page's HTML so that it displayed the appropriate
1660       company name and logo, without polluting your form parameters.
1661
1662       This call simply redispatches to "CGI.pm"'s param() method, so consult
1663       those docs for more information.
1664
1665   tmpl_param()
1666       This allows you to manipulate template parameters directly.  Extending
1667       the above example:
1668
1669           my $form = CGI::FormBuilder->new(template => 'some.tmpl');
1670
1671           my $company = $form->cgi_param('company');
1672           $form->tmpl_param(company => $company);
1673
1674       Then, in your template:
1675
1676           Hello, <tmpl_var company> employee!
1677           <p>
1678           Please fill out this form:
1679           <tmpl_var form-start>
1680           <!-- etc... -->
1681
1682       For really precise template control, you can actually create your own
1683       template object and then pass it directly to FormBuilder.  See
1684       CGI::FormBuilder::Template for more details.
1685
1686   sessionid()
1687       This gets and sets the sessionid, which is stored in the special form
1688       field "_sessionid". By default no session ids are generated or used.
1689       Rather, this is intended to provide a hook for you to easily integrate
1690       this with a session id module like "CGI::Session".
1691
1692       Since you can set the session id via the "_sessionid" field, you can
1693       pass it as an argument when first showing the form:
1694
1695           http://mydomain.com/forms/update_info.cgi?_sessionid=0123-091231
1696
1697       This would set things up so that if you called:
1698
1699           my $id = $form->sessionid;
1700
1701       This would get the value "0123-091231" in your script. Conversely, if
1702       you generate a new sessionid on your own, and wish to include it
1703       automatically, simply set is as follows:
1704
1705           $form->sessionid($id);
1706
1707       If the sessionid is set, and "header" is set, then FormBuilder will
1708       also automatically generate a cookie for you.
1709
1710       See "EXAMPLES" for "CGI::Session" example.
1711
1712   submitted()
1713       This returns the value of the "Submit" button if the form has been
1714       submitted, undef otherwise. This allows you to either test it in a
1715       boolean context:
1716
1717           if ($form->submitted) { ... }
1718
1719       Or to retrieve the button that was actually clicked on in the case of
1720       multiple submit buttons:
1721
1722           if ($form->submitted eq 'Update') {
1723               ...
1724           } elsif ($form->submitted eq 'Delete') {
1725               ...
1726           }
1727
1728       It's best to call validate() in conjunction with this to make sure the
1729       form validation works. To make sure you're getting accurate info, it's
1730       recommended that you name your forms with the "name" option described
1731       above.
1732
1733       If you're writing a multiple-form app, you should name your forms with
1734       the "name" option to ensure that you are getting an accurate return
1735       value from this sub. See the "name" option above, under render().
1736
1737       You can also specify the name of an optional field which you want to
1738       "watch" instead of the default "_submitted" hidden field. This is
1739       useful if you have a search form and also want to be able to link to it
1740       from other documents directly, such as:
1741
1742           mysearch.cgi?lookup=what+to+look+for
1743
1744       Normally, submitted() would return false since the "_submitted" field
1745       is not included. However, you can override this by saying:
1746
1747           $form->submitted('lookup');
1748
1749       Then, if the lookup field is present, you'll get a true value.
1750       (Actually, you'll still get the value of the "Submit" button if
1751       present.)
1752
1753   validate()
1754       This validates the form based on the validation criteria passed into
1755       new() via the "validate" option. In addition, you can specify
1756       additional criteria to check that will be valid for just that call of
1757       validate(). This is useful is you have to deal with different geos:
1758
1759           if ($location eq 'US') {
1760               $form->validate(state => 'STATE', zipcode => 'ZIPCODE');
1761           } else {
1762               $form->validate(state => '/^\w{2,3}$/');
1763           }
1764
1765       You can also provide a Data::FormValidator object as the first
1766       argument. In that case, the second argument (if present) will be
1767       interpreted as the name of the validation profile to use. A single
1768       string argument will also be interpreted as a validation profile name.
1769
1770       Note that if you pass args to your validate() function like this, you
1771       will not get JavaScript generated or required fields placed in bold.
1772       So, this is good for conditional validation like the above example, but
1773       for most applications you want to pass your validation requirements in
1774       via the "validate" option to the new() function, and just call the
1775       validate() function with no arguments.
1776
1777   confirm()
1778       The purpose of this function is to print out a static confirmation
1779       screen showing a short message along with the values that were
1780       submitted. It is actually just a special wrapper around render(),
1781       twiddling a couple options.
1782
1783       If you're using templates, you probably want to specify a separate
1784       success template, such as:
1785
1786           if ($form->submitted && $form->validate) {
1787               print $form->confirm(template => 'success.tmpl');
1788           } else {
1789               print $form->render(template => 'fillin.tmpl');
1790           }
1791
1792       So that you don't get the same screen twice.
1793
1794   mailconfirm()
1795       This sends a confirmation email to the named addresses. The "to"
1796       argument is required; everything else is optional. If no "from" is
1797       specified then it will be set to the address "auto-reply" since that is
1798       a common quasi-standard in the web app world.
1799
1800       This does not send any of the form results. Rather, it simply prints
1801       out a message saying the submission was received.
1802
1803   mailresults()
1804       This emails the form results to the specified address(es). By default
1805       it prints out the form results separated by a colon, such as:
1806
1807           name: Nate Wiger
1808           email: nate@wiger.org
1809           colors: red green blue
1810
1811       And so on. You can change this by specifying the "delimiter" and
1812       "joiner" options. For example this:
1813
1814           $form->mailresults(to => $to, delimiter => '=', joiner => ',');
1815
1816       Would produce an email like this:
1817
1818           name=Nate Wiger
1819           email=nate@wiger.org
1820           colors=red,green,blue
1821
1822       Note that now the last field ("colors") is separated by commas since
1823       you have multiple values and you specified a comma as your "joiner".
1824
1825   mailresults() with plugin
1826       Now you can also specify a plugin to use with mailresults, in the
1827       namespace "CGI::FormBuilder::Mail::*".  These plugins may depend on
1828       other libraries.  For example, this:
1829
1830           $form->mailresults(
1831               plugin          => 'FormatMultiPart',
1832               from            => 'Mark Hedges <hedges@ucsd.edu>',
1833               to              => 'Nate Wiger <nwiger@gmail.com>',
1834               smtp            => $smtp_host_or_ip,
1835               format          => 'plain',
1836           );
1837
1838       will send your mail formatted nicely in text using "Text::FormatTable".
1839       (And if you used format => 'html' it would use "HTML::QuickTable".)
1840
1841       This particular plugin uses "MIME::Lite" and "Net::SMTP" to communicate
1842       directly with the SMTP server, and does not rely on a shell escape.
1843       See CGI::FormBuilder::Mail::FormatMultiPart for more information.
1844
1845       This establishes a simple mail plugin implementation standard for your
1846       own mailresults() plugins.  The plugin should reside under the
1847       "CGI::FormBuilder::Mail::*" namespace. It should have a constructor
1848       new() which accepts a hash-as-array of named arg parameters, including
1849       form => $form.  It should have a mailresults() object method that does
1850       the right thing.  It should use "CGI::FormBuilder::Util" and puke() if
1851       something goes wrong.
1852
1853       Calling $form->mailresults( plugin => 'Foo', ... ) will load
1854       "CGI::FormBuilder::Mail::Foo" and will pass the FormBuilder object as a
1855       named param 'form' with all other parameters passed intact.
1856
1857       If it should croak, confess, die or otherwise break if something goes
1858       wrong, FormBuilder.pm will warn any errors and the built-in
1859       mailresults() method will still try.
1860
1861   mail()
1862       This is a more generic version of the above; it sends whatever is given
1863       as the "text" argument via email verbatim to the "to" address.  In
1864       addition, if you're not running "sendmail" you can specify the "mailer"
1865       parameter to give the path of your mailer. This option is accepted by
1866       the above functions as well.
1867

COMPATIBILITY

1869       The following methods are provided to make FormBuilder behave more like
1870       other modules, when desired.
1871
1872   header()
1873       Returns a "CGI.pm" header, but only if "header => 1" is set.
1874
1875   param()
1876       This is an alias for field(), provided for compatibility. However,
1877       while field() does act "compliantly" for easy use in "CGI::Session",
1878       "Apache::Request", etc, it is not 100% the same. As such, I recommend
1879       you use field() in your code, and let receiving objects figure the
1880       param() thing out when needed:
1881
1882           my $sess = CGI::Session->new(...);
1883           $sess->save_param($form);   # will see param()
1884
1885   query_string()
1886       This returns a query string similar to "CGI.pm", but ONLY containing
1887       form fields and any "keepextras", if specified. Other params are
1888       ignored.
1889
1890   self_url()
1891       This returns a self url, similar to "CGI.pm", but again ONLY with form
1892       fields.
1893
1894   script_name()
1895       An alias for "$form->action".
1896

STYLESHEETS (CSS)

1898       If the "stylesheet" option is enabled (by setting it to 1 or the path
1899       of a CSS file), then FormBuilder will automatically output style
1900       classes for every single form element:
1901
1902           fb              main form table
1903           fb_label        td containing field label
1904           fb_field        td containing field input tag
1905           fb_submit       td containing submit button(s)
1906
1907           fb_input        input types
1908           fb_select       select types
1909           fb_checkbox     checkbox types
1910           fb_radio        radio types
1911           fb_option       labels for checkbox/radio options
1912           fb_button       button types
1913           fb_hidden       hidden types
1914           fb_static       static types
1915
1916           fb_required     span around labels for required fields
1917           fb_invalid      span around labels for invalid fields
1918           fb_comment      span around field comment
1919           fb_error        span around field error message
1920
1921       Here's a simple example that you can put in "fb.css" which spruces up a
1922       couple basic form features:
1923
1924           /* FormBuilder */
1925           .fb {
1926               background: #ffc;
1927               font-family: verdana,arial,sans-serif;
1928               font-size: 10pt;
1929           }
1930
1931           .fb_label {
1932               text-align: right;
1933               padding-right: 1em;
1934           }
1935
1936           .fb_comment {
1937               font-size: 8pt;
1938               font-style: italic;
1939           }
1940
1941           .fb_submit {
1942               text-align: center;
1943           }
1944
1945           .fb_required {
1946               font-weight: bold;
1947           }
1948
1949           .fb_invalid {
1950               color: #c00;
1951               font-weight: bold;
1952           }
1953
1954           .fb_error {
1955               color: #c00;
1956               font-style: italic;
1957           }
1958
1959       Of course, if you're familiar with CSS, you know alot more is possible.
1960       Also, you can mess with all the id's (if you name your forms) to
1961       manipulate fields more exactly.
1962

EXAMPLES

1964       I find this module incredibly useful, so here are even more examples,
1965       pasted from sample code that I've written:
1966
1967   Ex1: order.cgi
1968       This example provides an order form, complete with validation of the
1969       important fields, and a "Cancel" button to abort the whole thing.
1970
1971           #!/usr/bin/perl
1972
1973           use strict;
1974           use CGI::FormBuilder;
1975
1976           my @states = my_state_list();   # you write this
1977
1978           my $form = CGI::FormBuilder->new(
1979                           method => 'post',
1980                           fields => [
1981                               qw(first_name last_name
1982                                  email send_me_emails
1983                                  address state zipcode
1984                                  credit_card expiration)
1985                           ],
1986
1987                           header => 1,
1988                           title  => 'Finalize Your Order',
1989                           submit => ['Place Order', 'Cancel'],
1990                           reset  => 0,
1991
1992                           validate => {
1993                                email   => 'EMAIL',
1994                                zipcode => 'ZIPCODE',
1995                                credit_card => 'CARD',
1996                                expiration  => 'MMYY',
1997                           },
1998                           required => 'ALL',
1999                           jsfunc => <<EOJS,
2000           // skip js validation if they clicked "Cancel"
2001           if (this._submit.value == 'Cancel') return true;
2002       EOJS
2003                      );
2004
2005           # Provide a list of states
2006           $form->field(name    => 'state',
2007                        options => \@states,
2008                        sortopts=> 'NAME');
2009
2010           # Options for mailing list
2011           $form->field(name    => 'send_me_emails',
2012                        options => [[1 => 'Yes'], [0 => 'No']],
2013                        value   => 0);   # "No"
2014
2015           # Check for valid order
2016           if ($form->submitted eq 'Cancel') {
2017               # redirect them to the homepage
2018               print $form->cgi->redirect('/');
2019               exit;
2020           }
2021           elsif ($form->submitted && $form->validate) {
2022               # your code goes here to do stuff...
2023               print $form->confirm;
2024           }
2025           else {
2026               # either first printing or needs correction
2027               print $form->render;
2028           }
2029
2030       This will create a form called "Finalize Your Order" that will provide
2031       a pulldown menu for the "state", a radio group for "send_me_emails",
2032       and normal text boxes for the rest. It will then validate all the
2033       fields, using specific patterns for those fields specified to
2034       "validate".
2035
2036   Ex2: order_form.cgi
2037       Here's an example that adds some fields dynamically, and uses the
2038       "debug" option spit out gook:
2039
2040           #!/usr/bin/perl
2041
2042           use strict;
2043           use CGI::FormBuilder;
2044
2045           my $form = CGI::FormBuilder->new(
2046                           method => 'post',
2047                           fields => [
2048                               qw(first_name last_name email
2049                                  address state zipcode)
2050                           ],
2051                           header => 1,
2052                           debug  => 2,    # gook
2053                           required => 'NONE',
2054                      );
2055
2056           # This adds on the 'details' field to our form dynamically
2057           $form->field(name => 'details',
2058                        type => 'textarea',
2059                        cols => '50',
2060                        rows => '10');
2061
2062           # And this adds user_name with validation
2063           $form->field(name  => 'user_name',
2064                        value => $ENV{REMOTE_USER},
2065                        validate => 'NAME');
2066
2067           if ($form->submitted && $form->validate) {
2068               # ... more code goes here to do stuff ...
2069               print $form->confirm;
2070           } else {
2071               print $form->render;
2072           }
2073
2074       In this case, none of the fields are required, but the "user_name"
2075       field will still be validated if filled in.
2076
2077   Ex3: ticket_search.cgi
2078       This is a simple search script that uses a template to layout the
2079       search parameters very precisely. Note that we set our options for our
2080       different fields and types.
2081
2082           #!/usr/bin/perl
2083
2084           use strict;
2085           use CGI::FormBuilder;
2086
2087           my $form = CGI::FormBuilder->new(
2088                           fields => [qw(type string status category)],
2089                           header => 1,
2090                           template => 'ticket_search.tmpl',
2091                           submit => 'Search',     # search button
2092                           reset  => 0,            # and no reset
2093                      );
2094
2095           # Need to setup some specific field options
2096           $form->field(name    => 'type',
2097                        options => [qw(ticket requestor hostname sysadmin)]);
2098
2099           $form->field(name    => 'status',
2100                        type    => 'radio',
2101                        options => [qw(incomplete recently_completed all)],
2102                        value   => 'incomplete');
2103
2104           $form->field(name    => 'category',
2105                        type    => 'checkbox',
2106                        options => [qw(server network desktop printer)]);
2107
2108           # Render the form and print it out so our submit button says "Search"
2109           print $form->render;
2110
2111       Then, in our "ticket_search.tmpl" HTML file, we would have something
2112       like this:
2113
2114           <html>
2115           <head>
2116             <title>Search Engine</title>
2117             <tmpl_var js-head>
2118           </head>
2119           <body bgcolor="white">
2120           <center>
2121           <p>
2122           Please enter a term to search the ticket database.
2123           <p>
2124           <tmpl_var form-start>
2125           Search by <tmpl_var field-type> for <tmpl_var field-string>
2126           <tmpl_var form-submit>
2127           <p>
2128           Status: <tmpl_var field-status>
2129           <p>
2130           Category: <tmpl_var field-category>
2131           <p>
2132           </form>
2133           </body>
2134           </html>
2135
2136       That's all you need for a sticky search form with the above HTML
2137       layout.  Notice that you can change the HTML layout as much as you want
2138       without having to touch your CGI code.
2139
2140   Ex4: user_info.cgi
2141       This script grabs the user's information out of a database and lets
2142       them update it dynamically. The DBI information is provided as an
2143       example, your mileage may vary:
2144
2145           #!/usr/bin/perl
2146
2147           use strict;
2148           use CGI::FormBuilder;
2149           use DBI;
2150           use DBD::Oracle
2151
2152           my $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass');
2153
2154           # We create a new form. Note we've specified very little,
2155           # since we're getting all our values from our database.
2156           my $form = CGI::FormBuilder->new(
2157                           fields => [qw(username password confirm_password
2158                                         first_name last_name email)]
2159                      );
2160
2161           # Now get the value of the username from our app
2162           my $user = $form->cgi_param('user');
2163           my $sth = $dbh->prepare("select * from user_info where user = '$user'");
2164           $sth->execute;
2165           my $default_hashref = $sth->fetchrow_hashref;
2166
2167           # Render our form with the defaults we got in our hashref
2168           print $form->render(values => $default_hashref,
2169                               title  => "User information for '$user'",
2170                               header => 1);
2171
2172   Ex5: add_part.cgi
2173       This presents a screen for users to add parts to an inventory database.
2174       Notice how it makes use of the "sticky" option. If there's an error,
2175       then the form is presented with sticky values so that the user can
2176       correct them and resubmit. If the submission is ok, though, then the
2177       form is presented without sticky values so that the user can enter the
2178       next part.
2179
2180           #!/usr/bin/perl
2181
2182           use strict;
2183           use CGI::FormBuilder;
2184
2185           my $form = CGI::FormBuilder->new(
2186                           method => 'post',
2187                           fields => [qw(sn pn model qty comments)],
2188                           labels => {
2189                               sn => 'Serial Number',
2190                               pn => 'Part Number'
2191                           },
2192                           sticky => 0,
2193                           header => 1,
2194                           required => [qw(sn pn model qty)],
2195                           validate => {
2196                                sn  => '/^[PL]\d{2}-\d{4}-\d{4}$/',
2197                                pn  => '/^[AQM]\d{2}-\d{4}$/',
2198                                qty => 'INT'
2199                           },
2200                           font => 'arial,helvetica'
2201                      );
2202
2203           # shrink the qty field for prettiness, lengthen model
2204           $form->field(name => 'qty',   size => 4);
2205           $form->field(name => 'model', size => 60);
2206
2207           if ($form->submitted) {
2208               if ($form->validate) {
2209                   # Add part to database
2210               } else {
2211                   # Invalid; show form and allow corrections
2212                   print $form->render(sticky => 1);
2213                   exit;
2214               }
2215           }
2216
2217           # Print form for next part addition.
2218           print $form->render;
2219
2220       With the exception of the database code, that's the whole application.
2221
2222   Ex6: Session Management
2223       This creates a session via "CGI::Session", and ties it in with
2224       FormBuilder:
2225
2226           #!/usr/bin/perl
2227
2228           use CGI::Session;
2229           use CGI::FormBuilder;
2230
2231           my $form = CGI::FormBuilder->new(fields => \@fields);
2232
2233           # Initialize session
2234           my $session = CGI::Session->new('driver:File',
2235                                           $form->sessionid,
2236                                           { Directory=>'/tmp' });
2237
2238           if ($form->submitted && $form->validate) {
2239               # Automatically save all parameters
2240               $session->save_param($form);
2241           }
2242
2243           # Ensure we have the right sessionid (might be new)
2244           $form->sessionid($session->id);
2245
2246           print $form->render;
2247
2248       Yes, it's pretty much that easy. See CGI::FormBuilder::Multi for how to
2249       tie this into a multi-page form.
2250

FREQUENTLY ASKED QUESTIONS (FAQ)

2252       There are a couple questions and subtle traps that seem to poke people
2253       on a regular basis. Here are some hints.
2254
2255   I'm confused. Why doesn't this work like CGI.pm?
2256       If you're used to "CGI.pm", you have to do a little bit of a brain
2257       shift when working with this module.
2258
2259       FormBuilder is designed to address fields as abstract entities.  That
2260       is, you don't create a "checkbox" or "radio group" per se.  Instead,
2261       you create a field for the data you want to collect.  The HTML
2262       representation is just one property of this field.
2263
2264       So, if you want a single-option checkbox, simply say something like
2265       this:
2266
2267           $form->field(name    => 'join_mailing_list',
2268                        options => ['Yes']);
2269
2270       If you want it to be checked by default, you add the "value" arg:
2271
2272           $form->field(name    => 'join_mailing_list',
2273                        options => ['Yes'],
2274                        value   => 'Yes');
2275
2276       You see, you're creating a field that has one possible option: "Yes".
2277       Then, you're saying its current value is, in fact, "Yes". This will
2278       result in FormBuilder creating a single-option field (which is a
2279       checkbox by default) and selecting the requested value (meaning that
2280       the box will be checked).
2281
2282       If you want multiple values, then all you have to do is specify
2283       multiple options:
2284
2285           $form->field(name    => 'join_mailing_list',
2286                        options => ['Yes', 'No'],
2287                        value   => 'Yes');
2288
2289       Now you'll get a radio group, and "Yes" will be selected for you!  By
2290       viewing fields as data entities (instead of HTML tags) you get much
2291       more flexibility and less code maintenance. If you want to be able to
2292       accept multiple values, simply use the "multiple" arg:
2293
2294           $form->field(name     => 'favorite_colors',
2295                        options  => [qw(red green blue)],
2296                        multiple => 1);
2297
2298       In all of these examples, to get the data back you just use the field()
2299       method:
2300
2301           my @colors = $form->field('favorite_colors');
2302
2303       And the rest is taken care of for you.
2304
2305   How do I make a multi-screen/multi-mode form?
2306       This is easily doable, but you have to remember a couple things. Most
2307       importantly, that FormBuilder only knows about those fields you've told
2308       it about. So, let's assume that you're going to use a special parameter
2309       called "mode" to control the mode of your application so that you can
2310       call it like this:
2311
2312           myapp.cgi?mode=list&...
2313           myapp.cgi?mode=edit&...
2314           myapp.cgi?mode=remove&...
2315
2316       And so on. You need to do two things. First, you need the "keepextras"
2317       option:
2318
2319           my $form = CGI::FormBuilder->new(..., keepextras => 1);
2320
2321       This will maintain the "mode" field as a hidden field across requests
2322       automatically. Second, you need to realize that since the "mode" is not
2323       a defined field, you have to get it via the cgi_param() method:
2324
2325           my $mode = $form->cgi_param('mode');
2326
2327       This will allow you to build a large multiscreen application easily,
2328       even integrating it with modules like "CGI::Application" if you want.
2329
2330       You can also do this by simply defining "mode" as a field in your
2331       "fields" declaration. The reason this is discouraged is because when
2332       iterating over your fields you'll get "mode", which you likely don't
2333       want (since it's not "real" data).
2334
2335   Why won't CGI::FormBuilder work with post requests?
2336       It will, but chances are you're probably doing something like this:
2337
2338           use CGI qw(:standard);
2339           use CGI::FormBuilder;
2340
2341           # Our "mode" parameter determines what we do
2342           my $mode = param('mode');
2343
2344           # Change our form based on our mode
2345           if ($mode eq 'view') {
2346               my $form = CGI::FormBuilder->new(
2347                               method => 'post',
2348                               fields => [qw(...)],
2349                          );
2350           } elsif ($mode eq 'edit') {
2351               my $form = CGI::FormBuilder->new(
2352                               method => 'post',
2353                               fields => [qw(...)],
2354                          );
2355           }
2356
2357       The problem is this: Once you read a "post" request, it's gone forever.
2358       In the above code, what you're doing is having "CGI.pm" read the "post"
2359       request (on the first call of param()).
2360
2361       Luckily, there is an easy solution. First, you need to modify your code
2362       to use the OO form of "CGI.pm". Then, simply specify the "CGI" object
2363       you create to the "params" option of FormBuilder:
2364
2365           use CGI;
2366           use CGI::FormBuilder;
2367
2368           my $cgi = CGI->new;
2369
2370           # Our "mode" parameter determines what we do
2371           my $mode = $cgi->param('mode');
2372
2373           # Change our form based on our mode
2374           # Note: since it is post, must specify the 'params' option
2375           if ($mode eq 'view') {
2376               my $form = CGI::FormBuilder->new(
2377                               method => 'post',
2378                               fields => [qw(...)],
2379                               params => $cgi      # get CGI params
2380                          );
2381           } elsif ($mode eq 'edit') {
2382               my $form = CGI::FormBuilder->new(
2383                               method => 'post',
2384                               fields => [qw(...)],
2385                               params => $cgi      # get CGI params
2386                          );
2387           }
2388
2389       Or, since FormBuilder gives you a cgi_param() function, you could also
2390       modify your code so you use FormBuilder exclusively, as in the previous
2391       question.
2392
2393   How can I change option XXX based on a conditional?
2394       To change an option, simply use its accessor at any time:
2395
2396           my $form = CGI::FormBuilder->new(
2397                           method => 'post',
2398                           fields => [qw(name email phone)]
2399                      );
2400
2401           my $mode = $form->cgi_param('mode');
2402
2403           if ($mode eq 'add') {
2404               $form->title('Add a new entry');
2405           } elsif ($mode eq 'edit') {
2406               $form->title('Edit existing entry');
2407
2408               # do something to select existing values
2409               my %values = select_values();
2410
2411               $form->values(\%values);
2412           }
2413           print $form->render;
2414
2415       Using the accessors makes permanent changes to your object, so be aware
2416       that if you want to reset something to its original value later, you'll
2417       have to first save it and then reset it:
2418
2419           my $style = $form->stylesheet;
2420           $form->stylesheet(0);       # turn off
2421           $form->stylesheet($style);  # original setting
2422
2423       You can also specify options to render(), although using the accessors
2424       is the preferred way.
2425
2426   How do I manually override the value of a field?
2427       You must specify the "force" option:
2428
2429           $form->field(name  => 'name_of_field',
2430                        value => $value,
2431                        force => 1);
2432
2433       If you don't specify "force", then the CGI value will always win.  This
2434       is because of the stateless nature of the CGI protocol.
2435
2436   How do I make it so that the values aren't shown in the form?
2437       Turn off sticky:
2438
2439           my $form = CGI::FormBuilder->new(... sticky => 0);
2440
2441       By turning off the "sticky" option, you will still be able to access
2442       the values, but they won't show up in the form.
2443
2444   I can't get "validate" to accept my regular expressions!
2445       You're probably not specifying them within single quotes. See the
2446       section on "validate" above.
2447
2448   Can FormBuilder handle file uploads?
2449       It sure can, and it's really easy too. Just change the "enctype" as an
2450       option to new():
2451
2452           use CGI::FormBuilder;
2453           my $form = CGI::FormBuilder->new(
2454                           enctype => 'multipart/form-data',
2455                           method  => 'post',
2456                           fields  => [qw(filename)]
2457                      );
2458
2459           $form->field(name => 'filename', type => 'file');
2460
2461       And then get to your file the same way as "CGI.pm":
2462
2463           if ($form->submitted) {
2464               my $file = $form->field('filename');
2465
2466               # save contents in file, etc ...
2467               open F, ">$dir/$file" or die $!;
2468               while (<$file>) {
2469                   print F;
2470               }
2471               close F;
2472
2473               print $form->confirm(header => 1);
2474           } else {
2475               print $form->render(header => 1);
2476           }
2477
2478       In fact, that's a whole file upload program right there.
2479

REFERENCES

2481       This really doesn't belong here, but unfortunately many people are
2482       confused by references in Perl. Don't be - they're not that tricky.
2483       When you take a reference, you're basically turning something into a
2484       scalar value. Sort of. You have to do this if you want to pass arrays
2485       intact into functions in Perl 5.
2486
2487       A reference is taken by preceding the variable with a backslash (\).
2488       In our examples above, you saw something similar to this:
2489
2490           my @fields = ('name', 'email');   # same as = qw(name email)
2491
2492           my $form = CGI::FormBuilder->new(fields => \@fields);
2493
2494       Here, "\@fields" is a reference. Specifically, it's an array reference,
2495       or "arrayref" for short.
2496
2497       Similarly, we can do the same thing with hashes:
2498
2499           my %validate = (
2500               name  => 'NAME';
2501               email => 'EMAIL',
2502           );
2503
2504           my $form = CGI::FormBuilder->new( ... validate => \%validate);
2505
2506       Here, "\%validate" is a hash reference, or "hashref".
2507
2508       Basically, if you don't understand references and are having trouble
2509       wrapping your brain around them, you can try this simple rule: Any time
2510       you're passing an array or hash into a function, you must precede it
2511       with a backslash. Usually that's true for CPAN modules.
2512
2513       Finally, there are two more types of references: anonymous arrayrefs
2514       and anonymous hashrefs. These are created with "[]" and "{}",
2515       respectively. So, for our purposes there is no real difference between
2516       this code:
2517
2518           my @fields = qw(name email);
2519           my %validate = (name => 'NAME', email => 'EMAIL');
2520
2521           my $form = CGI::FormBuilder->new(
2522                           fields   => \@fields,
2523                           validate => \%validate
2524                      );
2525
2526       And this code:
2527
2528           my $form = CGI::FormBuilder->new(
2529                           fields   => [ qw(name email) ],
2530                           validate => { name => 'NAME', email => 'EMAIL' }
2531                      );
2532
2533       Except that the latter doesn't require that we first create @fields and
2534       %validate variables.
2535

ENVIRONMENT VARIABLES

2537   FORMBUILDER_DEBUG
2538       This toggles the debug flag, so that you can control FormBuilder
2539       debugging globally. Helpful in mod_perl.
2540

NOTES

2542       Parameters beginning with a leading underscore are reserved for future
2543       use by this module. Use at your own peril.
2544
2545       The field() method has the alias param() for compatibility with other
2546       modules, allowing you to pass a $form around just like a $cgi object.
2547
2548       The output of the HTML generated natively may change slightly from
2549       release to release. If you need precise control, use a template.
2550
2551       Every attempt has been made to make this module taint-safe (-T).
2552       However, due to the way tainting works, you may run into the message
2553       "Insecure dependency" or "Insecure $ENV{PATH}". If so, make sure you
2554       are setting $ENV{PATH} at the top of your script.
2555

ACKNOWLEDGEMENTS

2557       This module has really taken off, thanks to very useful input, bug
2558       reports, and encouraging feedback from a number of people, including:
2559
2560           Norton Allen
2561           Mark Belanger
2562           Peter Billam
2563           Brad Bowman
2564           Jonathan Buhacoff
2565           Godfrey Carnegie
2566           Jakob Curdes
2567           Laurent Dami
2568           Bob Egert
2569           Peter Eichman
2570           Adam Foxson
2571           Jorge Gonzalez
2572           Florian Helmberger
2573           Mark Hedges
2574           Mark Houliston
2575           Victor Igumnov
2576           Robert James Kaes
2577           Dimitry Kharitonov
2578           Randy Kobes
2579           William Large
2580           Kevin Lubic
2581           Robert Mathews
2582           Mehryar
2583           Klaas Naajikens
2584           Koos Pol
2585           Shawn Poulson
2586           Victor Porton
2587           Dan Collis Puro
2588           Wolfgang Radke
2589           David Siegal
2590           Stephan Springl
2591           Ryan Tate
2592           John Theus
2593           Remi Turboult
2594           Andy Wardley
2595           Raphael Wegmann
2596           Emanuele Zeppieri
2597
2598       Thanks!
2599

SEE ALSO

2601       CGI::FormBuilder::Template, CGI::FormBuilder::Messages,
2602       CGI::FormBuilder::Multi, CGI::FormBuilder::Source::File,
2603       CGI::FormBuilder::Field, CGI::FormBuilder::Util,
2604       CGI::FormBuilder::Util, HTML::Template, Text::Template
2605       CGI::FastTemplate
2606

REVISION

2608       $Id: FormBuilder.pm 65 2006-09-07 18:11:43Z nwiger $
2609

AUTHOR

2611       Copyright (c) Nate Wiger <http://nateware.com>. All Rights Reserved.
2612
2613       This module is free software; you may copy this under the terms of the
2614       GNU General Public License, or the Artistic License, copies of which
2615       should have accompanied your Perl kit.
2616
2617
2618
2619perl v5.38.0                      2023-07-20               CGI::FormBuilder(3)
Impressum