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

METHODS

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

COMPATIBILITY

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

STYLESHEETS (CSS)

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

EXAMPLES

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

FREQUENTLY ASKED QUESTIONS (FAQ)

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

REFERENCES

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

ENVIRONMENT VARIABLES

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

NOTES

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

ACKNOWLEDGEMENTS

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

SEE ALSO

2598       CGI::FormBuilder::Template, CGI::FormBuilder::Messages,
2599       CGI::FormBuilder::Multi, CGI::FormBuilder::Source::File,
2600       CGI::FormBuilder::Field, CGI::FormBuilder::Util,
2601       CGI::FormBuilder::Util, HTML::Template, Text::Template
2602       CGI::FastTemplate
2603

REVISION

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

AUTHOR

2608       Copyright (c) 2000-2006 Nate Wiger <nate@wiger.org>. All Rights
2609       Reserved.
2610
2611       This module is free software; you may copy this under the terms of the
2612       GNU General Public License, or the Artistic License, copies of which
2613       should have accompanied your Perl kit.
2614
2615
2616
2617perl v5.12.0                      2007-03-02               CGI::FormBuilder(3)
Impressum