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

METHODS

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

COMPATIBILITY

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

STYLESHEETS (CSS)

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

EXAMPLES

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

FREQUENTLY ASKED QUESTIONS (FAQ)

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

REFERENCES

2510       This really doesn't belong here, but unfortunately many people are con‐
2511       fused by references in Perl. Don't be - they're not that tricky.  When
2512       you take a reference, you're basically turning something into a scalar
2513       value. Sort of. You have to do this if you want to pass arrays intact
2514       into functions in Perl 5.
2515
2516       A reference is taken by preceding the variable with a backslash (\).
2517       In our examples above, you saw something similar to this:
2518
2519           my @fields = ('name', 'email');   # same as = qw(name email)
2520
2521           my $form = CGI::FormBuilder->new(fields => \@fields);
2522
2523       Here, "\@fields" is a reference. Specifically, it's an array reference,
2524       or "arrayref" for short.
2525
2526       Similarly, we can do the same thing with hashes:
2527
2528           my %validate = (
2529               name  => 'NAME';
2530               email => 'EMAIL',
2531           );
2532
2533           my $form = CGI::FormBuilder->new( ... validate => \%validate);
2534
2535       Here, "\%validate" is a hash reference, or "hashref".
2536
2537       Basically, if you don't understand references and are having trouble
2538       wrapping your brain around them, you can try this simple rule: Any time
2539       you're passing an array or hash into a function, you must precede it
2540       with a backslash. Usually that's true for CPAN modules.
2541
2542       Finally, there are two more types of references: anonymous arrayrefs
2543       and anonymous hashrefs. These are created with "[]" and "{}", respec‐
2544       tively. So, for our purposes there is no real difference between this
2545       code:
2546
2547           my @fields = qw(name email);
2548           my %validate = (name => 'NAME', email => 'EMAIL');
2549
2550           my $form = CGI::FormBuilder->new(
2551                           fields   => \@fields,
2552                           validate => \%validate
2553                      );
2554
2555       And this code:
2556
2557           my $form = CGI::FormBuilder->new(
2558                           fields   => [ qw(name email) ],
2559                           validate => { name => 'NAME', email => 'EMAIL' }
2560                      );
2561
2562       Except that the latter doesn't require that we first create @fields and
2563       %validate variables.
2564

ENVIRONMENT VARIABLES

2566       FORMBUILDER_DEBUG
2567
2568       This toggles the debug flag, so that you can control FormBuilder debug‐
2569       ging globally. Helpful in mod_perl.
2570

NOTES

2572       Parameters beginning with a leading underscore are reserved for future
2573       use by this module. Use at your own peril.
2574
2575       The "field()" method has the alias "param()" for compatibility with
2576       other modules, allowing you to pass a $form around just like a $cgi
2577       object.
2578
2579       The output of the HTML generated natively may change slightly from
2580       release to release. If you need precise control, use a template.
2581
2582       Every attempt has been made to make this module taint-safe (-T).  How‐
2583       ever, due to the way tainting works, you may run into the message
2584       "Insecure dependency" or "Insecure $ENV{PATH}". If so, make sure you
2585       are setting $ENV{PATH} at the top of your script.
2586

ACKNOWLEDGEMENTS

2588       This module has really taken off, thanks to very useful input, bug
2589       reports, and encouraging feedback from a number of people, including:
2590
2591           Norton Allen
2592           Mark Belanger
2593           Peter Billam
2594           Brad Bowman
2595           Jonathan Buhacoff
2596           Godfrey Carnegie
2597           Jakob Curdes
2598           Laurent Dami
2599           Bob Egert
2600           Peter Eichman
2601           Adam Foxson
2602           Jorge Gonzalez
2603           Florian Helmberger
2604           Mark Hedges
2605           Mark Houliston
2606           Victor Igumnov
2607           Robert James Kaes
2608           Dimitry Kharitonov
2609           Randy Kobes
2610           William Large
2611           Kevin Lubic
2612           Robert Mathews
2613           Mehryar
2614           Klaas Naajikens
2615           Koos Pol
2616           Shawn Poulson
2617           Dan Collis Puro
2618           David Siegal
2619           Stephan Springl
2620           Ryan Tate
2621           John Theus
2622           Remi Turboult
2623           Andy Wardley
2624           Raphael Wegmann
2625           Emanuele Zeppieri
2626
2627       Thanks!
2628

SEE ALSO

2630       CGI::FormBuilder::Template, CGI::FormBuilder::Messages, CGI::Form‐
2631       Builder::Multi, CGI::FormBuilder::Source::File, CGI::Form‐
2632       Builder::Field, CGI::FormBuilder::Util, CGI::FormBuilder::Util,
2633       HTML::Template, Text::Template CGI::FastTemplate
2634

REVISION

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

AUTHOR

2639       Copyright (c) 2000-2006 Nate Wiger <nate@wiger.org>. All Rights
2640       Reserved.
2641
2642       This module is free software; you may copy this under the terms of the
2643       GNU General Public License, or the Artistic License, copies of which
2644       should have accompanied your Perl kit.
2645
2646
2647
2648perl v5.8.8                       2007-03-02               CGI::FormBuilder(3)
Impressum