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

COMPATIBILITY

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

STYLESHEETS (CSS)

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

EXAMPLES

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

FREQUENTLY ASKED QUESTIONS (FAQ)

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

REFERENCES

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

ENVIRONMENT VARIABLES

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

NOTES

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

ACKNOWLEDGEMENTS

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

SEE ALSO

2604       CGI::FormBuilder::Template, CGI::FormBuilder::Messages,
2605       CGI::FormBuilder::Multi, CGI::FormBuilder::Source::File,
2606       CGI::FormBuilder::Field, CGI::FormBuilder::Util,
2607       CGI::FormBuilder::Util, HTML::Template, Text::Template
2608       CGI::FastTemplate
2609

REVISION

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

AUTHOR

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