.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "FormBuilder 3" .TH FormBuilder 3 "2003-09-19" "perl v5.8.4" "User Contributed Perl Documentation" .SH "NAME" CGI::FormBuilder \- Easily generate and process stateful forms .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use CGI::FormBuilder; .Ve .PP .Vb 2 \& # Let's assume we did a DBI query to get existing values \& my $dbval = $sth->fetchrow_hashref; .Ve .PP .Vb 8 \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/name email phone gender/], \& values => $dbval, \& validate => { email => 'EMAIL', phone => 'PHONE' }, \& required => 'ALL', \& font => 'arial,helvetica', \& ); .Ve .PP .Vb 2 \& # Change gender field to have options \& $form->field(name => 'gender', options => [qw/Male Female/]); .Ve .PP .Vb 2 \& if ($form->submitted && $form->validate) { \& my $fields = $form->field; # get form fields as hashref .Ve .PP .Vb 3 \& # Do something to update your data (you would write this) \& do_data_update($fields->{name}, $fields->{email}, \& $fields->{phone}, $fields->{gender}); .Ve .PP .Vb 2 \& # Show confirmation screen \& print $form->confirm(header => 1); .Ve .PP .Vb 2 \& # Email the person a brief confirmation \& $form->mailconfirm(to => $fields->{email}); .Ve .PP .Vb 4 \& } else { \& # Print out the form \& print $form->render(header => 1); \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This documentation is very extensive, and likely all you will need. However, there is even more online, as well as examples and tutorials, at: .PP .Vb 1 \& www.formbuilder.org .Ve .PP You should also consider joining the mailing list by sending an email to: .PP .Vb 1 \& fbusers-subscribe@formbuilder.org .Ve .PP You are encouraged to visit the website, even if you are a longtime user, as there are a number of hints and tricks that you may find useful. .Sh "Overview" .IX Subsection "Overview" I hate generating and processing forms. Hate it, hate it, hate it, hate it. My forms almost always end up looking the same, and almost always end up doing the same thing. Unfortunately, there really haven't been any tools out there that streamline the process. Many modules simply substitute Perl for \s-1HTML\s0 code: .PP .Vb 2 \& # The manual way \& print qq(); .Ve .PP .Vb 2 \& # The module way \& print input(-name => 'email', -type => 'text', -size => '20'); .Ve .PP The problem is, that doesn't really gain you anything. You still have just as much code. Modules like the venerable \f(CW\*(C`CGI.pm\*(C'\fR are great for processing parameters, but they don't save you much time when trying to generate and process forms. .PP The goal of \f(CW\*(C`CGI::FormBuilder\*(C'\fR (\fBFormBuilder\fR) is to provide an easy way for you to generate and process \s-1CGI\s0 form-based applications. This module is designed to be smart in that it figures a lot of stuff out for you. As a result, \fBFormBuilder\fR gives you about a \fB4:1\fR ratio of the code it generates versus what you have to write. .PP For example, if you have multiple values for a field, it sticks them in a radio, checkbox, or select group, depending on some factors. It will also automatically name fields for you in human-readable labels depending on the field names, and lay everything out in a nicely formatted table. It will even title the form based on the name of the script itself (\f(CW\*(C`order_form.cgi\*(C'\fR becomes \*(L"Order Form\*(R"). .PP Plus, \fBFormBuilder\fR provides you full-blown validation for your fields, including some useful builtin patterns. It will even generate JavaScript validation routines on the fly! And, of course, it maintains state (\*(L"stickiness\*(R") across submissions, with hooks provided for you to plugin your own sessionid module such as \f(CW\*(C`Apache::Session\*(C'\fR. .PP And though it's smart, it allows you to customize it as well. For example, if you really want something to be a checkbox, you can make it a checkbox. And, if you really want something to be output a specific way, you can even specify the name of an \f(CW\*(C`HTML::Template\*(C'\fR or Template Toolkit (\f(CW\*(C`Template\*(C'\fR) compatible template which will be automatically filled in, statefully. .Sh "Walkthrough" .IX Subsection "Walkthrough" Let's walk through a whole example to see how \fBFormBuilder\fR works. The basic usage is straightforward, and has these steps: .IP "1." 4 Create a new \f(CW\*(C`CGI::FormBuilder\*(C'\fR object with the proper options .IP "2." 4 Modify any fields that may need fiddling with .IP "3." 4 Validate the form, if applicable, and print it out .PP \&\fBFormBuilder\fR is designed to do the tedious grunt work for you. In fact, a whole form-based application can be output with nothing more than this: .PP .Vb 1 \& use CGI::FormBuilder; .Ve .PP .Vb 1 \& my @fields = qw(name email password confirm_password zipcode); .Ve .PP .Vb 1 \& my $form = CGI::FormBuilder->new(fields => \e@fields); .Ve .PP .Vb 1 \& print $form->render(header => 1); .Ve .PP Not only does this generate about 4 times as much HTML-compliant code as the above Perl code, but it also keeps values statefully across submissions, even when multiple values are selected. And if you do nothing more than add the \f(CW\*(C`validate\*(C'\fR option to \f(CW\*(C`new()\*(C'\fR: .PP .Vb 4 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& validate => {email => 'EMAIL'} \& ); .Ve .PP You now get a whole set of JavaScript validation code, as well as Perl hooks for validation. In total you get about \fB6 times\fR the amount of code generated versus written. Plus, statefulness and validation are handled for you, automatically. .PP Let's keep building on this example. Say we decide that we really like our form fields and their stickiness, but we need to change a couple things. For one, we want the page to be laid out very precisely. No problem! We simply create an \f(CW\*(C`HTML::Template\*(C'\fR compatible template and tell our module to use that. The \f(CW\*(C`HTML::Template\*(C'\fR module uses special \s-1HTML\s0 tags to print out variables. All you have to do in your template is create one for each field that you're printing, as well as one for the form header itself: .PP .Vb 17 \& \& \& <tmpl_var form-title> \& \& \& \&

User Information

\& Please fill out the following information: \& \&

Your full name: \&

Your email address: \&

Choose a password: \&

Please confirm it: \&

Your home zipcode: \&

\& \& .Ve .PP Then, all you need to do in your Perl is add the \f(CW\*(C`template\*(C'\fR option: .PP .Vb 3 \& my $form = CGI::FormBuilder->new(fields => \e@fields, \& validate => {email => 'EMAIL'}, \& template => 'userinfo.tmpl'); .Ve .PP And the rest of the code stays the same. .PP You can also do a similar thing using the Template Toolkit (http://template\-toolkit.org/) to generate the form. This time, specify the \f(CW\*(C`template\*(C'\fR option as a hashref which includes the \&\f(CW\*(C`type\*(C'\fR option set to \f(CW\*(C`TT2\*(C'\fR and the \f(CW\*(C`template\*(C'\fR option to denote the name of the template you want processed. You can also add \&\f(CW\*(C`variable\*(C'\fR as an option (among others) to denote the variable name that you want the form data to be referenced by. .PP .Vb 8 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'TT2', \& template => 'userinfo.tmpl', \& variable => 'form', \& } \& ); .Ve .PP The template might look something like this: .PP .Vb 21 \& \& \& [% form.title %] \& [% form.jshead %] \& \& \& [% form.start %] \& \& [% FOREACH field = form.fields %] \& \& \& \& \& [% END %] \& \& \& \&
\& [% field.required \& ? "$field.label" \& : field.label \& %] \& \& [% IF field.invalid %] \& Missing or invalid entry, please try again. \&
\& [% END %] .Ve .PP .Vb 13 \& [% field.field %] \&
\& [% form.submit %] \&
\& [% form.end %] \& \& .Ve .PP So, as you can see, there is plugin capability for \fBFormBuilder\fR to basically \*(L"run\*(R" the two major templating engines, \fBHTML::Template\fR and \fBTemplate Toolkit\fR. .PP Now, back to \fBFormBuilder\fR. Let's assume that we want to validate our form on the server side, which is common since the user may not be running JavaScript. All we have to add is the statement: .PP .Vb 1 \& $form->validate; .Ve .PP Which will go through the form, checking each value specified to the validate option to see if it's ok. If there's a problem, then that field is highlighted so that when you print it out the errors will be apparent. .PP Of course, the above returns a truth value, which we should use to see if the form was valid. That way, we can only fiddle our database or whatever if everything looks good. We can then use our \f(CW\*(C`confirm()\*(C'\fR method to print out a generic results page: .PP .Vb 6 \& if ($form->validate) { \& # form was good, let's update database ... \& print $form->confirm; \& } else { \& print $form->render; \& } .Ve .PP The \f(CW\*(C`validate()\*(C'\fR method will use whatever criteria were passed into \f(CW\*(C`new()\*(C'\fR via the \f(CW\*(C`validate\*(C'\fR parameter to check the form submission to make sure it's correct. .PP However, we really only want to do this after our form has been submitted, since this could otherwise result in our form showing errors even though the user hasn't gotten a chance to fill it out yet. As such, we can check for whether the form has been submitted yet by wrapping the above with: .PP .Vb 6 \& if ($form->submitted && $form->validate) { \& # form was good, let's update database ... \& print $form->confirm; \& } else { \& print $form->render; \& } .Ve .PP Of course, this module wouldn't be really smart if it didn't provide some more stuff for you. A lot of times, we want to send a simple confirmation email to the user (and maybe ourselves) saying that the form has been submitted. Just use \f(CW\*(C`mailconfirm()\*(C'\fR: .PP .Vb 2 \& $form->mailconfirm(to => $form->field('email'), \& from => 'auto-reply'); .Ve .PP With \fBFormBuilder\fR, any default values you specify are automatically overridden by whatever the user enters into the form and submits. These can then be gotten to by using the \f(CW\*(C`field()\*(C'\fR method: .PP .Vb 1 \& my $email = $form->field(name => 'email'); .Ve .PP Of course, like \f(CW\*(C`CGI.pm's param()\*(C'\fR you can just specify the name of the field when getting a value back: .PP .Vb 1 \& my $email = $form->field('email'); .Ve .PP \&\fBFormBuilder\fR is good at giving you the data that you should be getting. That is, let's say that you initially setup your \&\f(CW$form\fR object to use a hash of existing values from a database select or something. Then, you \f(CW\*(C`render()\*(C'\fR the form, the user fills it out, and submits it. When you call \f(CW\*(C`field()\*(C'\fR, you'll get whatever the correct value is, either the default or what the user entered across the \s-1CGI\s0. .PP So, our complete code thus far looks like this: .PP .Vb 1 \& use CGI::FormBuilder; .Ve .PP .Vb 1 \& my @fields = qw(name email password confirm_password zipcode); .Ve .PP .Vb 6 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& validate => { email => 'EMAIL' }, \& template => 'userinfo.tmpl', \& header => 1 \& ); .Ve .PP .Vb 4 \& if ($form->submitted && $form->validate) { \& # form was ok, let's update database (you write this part) \& my $fields = $form->field; # get all fields as hashref \& do_data_update($fields); .Ve .PP .Vb 2 \& # show a confirmation message \& print $form->confirm; .Ve .PP .Vb 7 \& # and send them email about their submission \& $form->mailconfirm(to => $form->field('email'), \& from => 'auto-reply'); \& } else { \& # print the form for them to fill out \& print $form->render; \& } .Ve .PP You may be surprised to learn that for many applications, the above is probably all you'll need. Just fill in the parts that affect what you want to do (like the database code), and you're on your way. .SH "REFERENCES" .IX Header "REFERENCES" This really doesn't belong here, but unfortunately many people are confused by references in Perl. Don't be \- they're not that tricky. When you take a reference, you're basically turning something into a scalar value. Sort of. You have to do this if you want to pass arrays intact into functions in Perl 5. .PP A reference is taken by preceding the variable with a backslash (\e). In our examples above, you saw something similar to this: .PP .Vb 1 \& my @fields = ('name', 'email'); # same as = qw(name email) .Ve .PP .Vb 1 \& my $form = CGI::FormBuilder->new(fields => \e@fields); .Ve .PP Here, \f(CW\*(C`\e@fields\*(C'\fR is a reference. Specifically, it's an array reference, or \*(L"arrayref\*(R" for short. .PP Similarly, we can do the same thing with hashes: .PP .Vb 4 \& my %validate = ( \& name => 'NAME'; \& email => 'EMAIL', \& ); .Ve .PP .Vb 1 \& my $form = CGI::FormBuilder->new( ... validate => \e%validate); .Ve .PP Here, \f(CW\*(C`\e%validate\*(C'\fR is a hash reference, or \*(L"hashref\*(R". .PP Basically, if you don't understand references and are having trouble wrapping your brain around them, you can try this simple rule: Any time you're passing an array or hash into a function, you must precede it with a backslash. Usually that's true for \s-1CPAN\s0 modules. .PP Finally, there are two more types of references: anonymous arrayrefs and anonymous hashrefs. These are created with \f(CW\*(C`[]\*(C'\fR and \f(CW\*(C`{}\*(C'\fR, respectively. So, for our purposes there is no real difference between this code: .PP .Vb 2 \& my @fields = qw(name email); \& my %validate = (name => 'NAME', email => 'EMAIL'); .Ve .PP .Vb 4 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& validate => \e%validate \& ); .Ve .PP And this code: .PP .Vb 4 \& my $form = CGI::FormBuilder->new( \& fields => [ qw(name email) ], \& validate => { name => 'NAME', email => 'EMAIL' } \& ); .Ve .PP Except that the latter doesn't require that we first create \&\f(CW@fields\fR and \f(CW%validate\fR variables. .PP Now back to our regularly-scheduled program... .SH "FUNCTIONS" .IX Header "FUNCTIONS" Of course, in the spirit of flexibility this module takes a bizillion different options. None of these are mandatory \- you can call the \&\f(CW\*(C`new()\*(C'\fR constructor without any fields, but your form will be really really short. :\-) .PP This documentation is very extensive, but can be a bit dizzying due to the enormous number of options that let you tweak just about anything. As such, I recommend that if this is your first time using this module, you stop and visit: .PP .Vb 1 \& www.formbuilder.org .Ve .PP And click on \*(L"Tutorials\*(R" and \*(L"Examples\*(R". Then, use the following section as a reference later on. .Sh "\fInew()\fP" .IX Subsection "new()" This is the constructor, and must be called very first. It returns a \f(CW$form\fR object, which you can then modify and print out to create the form. This function accepts all of the options listed under \f(CW\*(C`render()\*(C'\fR below. In addition, it takes 6 options that can only be specified to \f(CW\*(C`new()\*(C'\fR: .IP "fields => \e@array | \e%hash" 4 .IX Item "fields => @array | %hash" The \f(CW\*(C`fields\*(C'\fR option takes an arrayref of fields to use in the form. The fields will be printed out in the same order they are specified. This option is needed if you expect your form to have any fields, and is \fIthe\fR central option to FormBuilder. .Sp You can also specify a hashref of key/value pairs. The advantage is you can then bypass the \f(CW\*(C`values\*(C'\fR option. However, the big disadvantage is you cannot control the order of the fields. This is ok if you're using a template, but in real-life it turns out that passing a hashref to \f(CW\*(C`fields\*(C'\fR is not very useful. .ie n .IP "name => $string" 4 .el .IP "name => \f(CW$string\fR" 4 .IX Item "name => $string" This option can \fBonly\fR be specified to \f(CW\*(C`new()\*(C'\fR but not to \f(CW\*(C`render()\*(C'\fR. .Sp This names the form. It is optional, but if you specify it you must do so in \f(CW\*(C`new()\*(C'\fR since the name is then used to alter how variables are created and looked up. .Sp This option has an important side effect. When used, it renames several key variables and functions according to the name of the form. This allows you to (a) use multiple forms in a sequential application and (b) display multiple forms inline in one document. If you're trying to build a complex multi-form app and are having problems, try naming your forms. .ie n .IP "params => $object" 4 .el .IP "params => \f(CW$object\fR" 4 .IX Item "params => $object" This specifies an object from which the parameters should be derived. The object must have a \f(CW\*(C`param()\*(C'\fR method which will return values for each parameter by name. By default a \s-1CGI\s0 object will be automatically created and used. .Sp However, you will want to specify this if you're using \f(CW\*(C`mod_perl\*(C'\fR: .Sp .Vb 2 \& use Apache::Request; \& use CGI::FormBuilder; .Ve .Sp .Vb 6 \& sub handler { \& my $r = Apache::Request->new(shift); \& my $form = CGI::FormBuilder->new(... params => $r); \& # ... \& print $form->render; \& } .Ve .Sp Or, if you need to initialize a \f(CW\*(C`CGI.pm\*(C'\fR object separately and are using a \f(CW\*(C`POST\*(C'\fR form method: .Sp .Vb 2 \& use CGI; \& use CGI::FormBuilder; .Ve .Sp .Vb 4 \& my $q = new CGI; \& my $mode = $q->param('mode'); \& # do stuff based on mode ... \& my $form = CGI::FormBuilder->new(... params => $q); .Ve .Sp The above example would allow you to access \s-1CGI\s0 parameters directly via \f(CW\*(C`$q\->param\*(C'\fR (however, note that you could get the same functionality by using \f(CW\*(C`$form\->cgi_param\*(C'\fR). .IP "validate => \e%hash" 4 .IX Item "validate => %hash" This option takes a hashref of key/value pairs. Each key is the name of a field from the \f(CW\*(C`fields\*(C'\fR option, or the string \f(CW\*(C`ALL\*(C'\fR in which case it applies to all fields. Each value is one of the following: .Sp .Vb 6 \& - a regular expression to match the field against \& - an arrayref of values of which the field must be one \& - a string that corresponds to one of the builtin patterns \& - a string containing a literal code comparison to do \& - a reference to a sub to be used to validate the field \& (the sub will receive the value to check as the first arg) .Ve .Sp In addition, each of these can also be grouped together as: .Sp .Vb 2 \& - a hashref containing pairings of comparisons to do for \& the two different languages, "javascript" and "perl" .Ve .Sp By default, the \f(CW\*(C`validate\*(C'\fR option also sets up each field so that it is required. However, if you specify the \f(CW\*(C`required\*(C'\fR option, then only those fields explicitly listed would be required, and the rest would only be validated if filled in. See the \f(CW\*(C`required\*(C'\fR option for more details. .Sp Let's look at a concrete example: .Sp .Vb 1 \& my $form = CGI::FormBuilder->new( .Ve .Sp .Vb 2 \& fields => [qw/username password confirm_password \& first_name last_name email/], .Ve .Sp .Vb 11 \& validate => { username => [qw/nate jim bob/], \& first_name => '/^\ew+$/', # note the \& last_name => '/^\ew+$/', # single quotes! \& email => 'EMAIL', \& password => \e&check_password, \& confirm_password => { \& javascript => '== form.password.value', \& perl => 'eq $form->field("password")' \& } \& } \& ); .Ve .Sp .Vb 8 \& # simple sub example to check the password \& sub check_password ($) { \& my $v = shift; # first arg is value \& return unless $v =~ /^.{6,8}/; # 6-8 chars \& return if $v eq "password"; # dummy check \& return unless passes_crack($v); # you write "passes_crack()" \& return 1; \& } .Ve .Sp This would create both JavaScript and Perl conditionals on the fly that would ensure: .Sp .Vb 6 \& - "username" was either "nate", "jim", or "bob" \& - "first_name" and "last_name" both match the regex's specified \& - "email" is a valid EMAIL format \& - "password" passes the checks done by check_password(), meaning \& that the sub returns true \& - "confirm_password" is equal to the "password" field .Ve .Sp \&\fBAny regular expressions you specify must be enclosed in single quotes because they need to be used in both JavaScript and Perl code.\fR As such, specifying a \f(CW\*(C`qr//\*(C'\fR will \s-1NOT\s0 work. .Sp Note that for both the \f(CW\*(C`javascript\*(C'\fR and \f(CW\*(C`perl\*(C'\fR hashref code options, the form will be present as the variable named \f(CW\*(C`form\*(C'\fR. For the Perl code, you actually get a complete \f(CW$form\fR object meaning that you have full access to all its methods (although the \f(CW\*(C`field()\*(C'\fR method is probably the only one you'll need for validation). .Sp In addition to taking any regular expression you'd like, the \&\f(CW\*(C`validate\*(C'\fR option also has many builtin defaults that can prove helpful: .Sp .Vb 27 \& VALUE - is any type of non-null value \& WORD - is a word (\ew+) \& NAME - matches [a-zA-Z] only \& FNAME - person's first name, like "Jim" or "Joe-Bob" \& LNAME - person's last name, like "Smith" or "King, Jr." \& NUM - number, decimal or integer \& INT - integer \& FLOAT - floating-point number \& PHONE - phone number in form "123-456-7890" or "(123) 456-7890" \& INTPHONE- international phone number in form "+prefix local-number" \& EMAIL - email addr in form "name@host.domain" \& CARD - credit card, including Amex, with or without -'s \& DATE - date in format MM/DD/YYYY or DD/MM/YYYY \& MMYY - date in format MM/YY or MMYY \& MMYYYY - date in format MM/YYYY or MMYYYY \& CCMM - strict checking for valid credit card 2-digit month ([0-9]|1[012]) \& CCYY - valid credit card 2-digit year \& ZIPCODE - US postal code in format 12345 or 12345-6789 \& STATE - valid two-letter state in all uppercase \& IPV4 - valid IPv4 address \& NETMASK - valid IPv4 netmask \& FILE - UNIX format filename (/usr/bin) \& WINFILE - Windows format filename (C:\ewindows\esystem) \& MACFILE - MacOS format filename (folder:subfolder:subfolder) \& HOST - valid hostname (some-name) \& DOMAIN - valid domainname (www.i-love-bacon.com) \& ETHER - valid ethernet address using either : or . as separators .Ve .Sp I know some of the above are US\-centric, but then again that's where I live. :\-) So if you need different processing just create your own regular expression and pass it in. If there's something really useful let me know and maybe I'll add it. .ie n .IP "messages => $filename | \e%hash" 4 .el .IP "messages => \f(CW$filename\fR | \e%hash" 4 .IX Item "messages => $filename | %hash" This option allows you to customize basically all the messages this module outputs. This is useful if you are writing a multilingual application, or are just anal and want the messages exactly right. .Sp The messaging system is simple, as it borrows somewhat from \f(CW\*(C`getttext()\*(C'\fR. Each message displayed is given a unique key. If you specify a custom message for a given key, then that message is used. Otherwise, the default is printed. Note that it is up to you to figure out what to pass in \- there is no magic \f(CW\*(C`LC_MESSAGES\*(C'\fR mysterium to this module. .Sp For example, let's say you wrote a script that needed to display custom JavaScript error messages. You could do something like this: .Sp .Vb 2 \& # Get language requested \& my $lang = $ENV{HTTP_ACCEPT_LANGUAGE} || 'en'; .Ve .Sp .Vb 2 \& # Get the appropriate file \& my $langfile = "/languages/formbuilder/messages.$lang"; .Ve .Sp .Vb 4 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& messages => $langfile, \& ); .Ve .Sp .Vb 1 \& print $form->render; .Ve .Sp Then, your language file would contain the following: .Sp .Vb 4 \& # FormBuilder messages for "en" locale \& js_invalid_start %s error(s) were found in your form:\en \& js_invalid_end Fix these fields and try again! \& js_invalid_select - You must choose an option for the "%s" field\en .Ve .Sp Alternatively, you could specify this directly as a hashref: .Sp .Vb 8 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& messages => { \& js_invalid_start => '%s error(s) were found in your form:\en', \& js_invalid_end => 'Fix these fields and try again!', \& js_invalid_select => '- Choose an option from the "%s" list\en', \& } \& ); .Ve .Sp Although in practice this is rarely useful, unless you just want to tweak one or two things. .Sp This system is easy, are there are many many messages that can be customized. Here is a list of the fields that can be customized, along with their default values. .Sp .Vb 2 \& js_invalid_start %s error(s) were encountered with your submission: \& js_invalid_end Please correct these fields and try again. .Ve .Sp .Vb 7 \& js_invalid_input - You must enter a valid value for the "%s" field \& js_invalid_select - You must choose an option for the "%s" field \& js_invalid_checkbox - You must choose an option for the "%s" field \& js_invalid_radio - You must choose an option for the "%s" field \& js_invalid_password - You must enter a valid value for the "%s" field \& js_invalid_textarea - You must fill in the "%s" field \& js_invalid_file - You must specify a valid file for the "%s" field .Ve .Sp .Vb 1 \& form_required_text

Fields shown in bold are required. .Ve .Sp .Vb 3 \& form_invalid_text

%s error(s) were encountered with your submission. \& Please correct the fields \& highlighted below. .Ve .Sp .Vb 1 \& form_invalid_color red .Ve .Sp .Vb 1 \& form_confirm_text Success! Your submission has been received %s. .Ve .Sp .Vb 7 \& form_invalid_input You must enter a valid value \& form_invalid_select You must choose an option from this list \& form_invalid_checkbox You must choose an option from this group \& form_invalid_radio You must choose an option from this group \& form_invalid_password You must enter a valid value \& form_invalid_textarea You must fill in this field \& form_invalid_file You must specify a valid filename .Ve .Sp .Vb 3 \& form_select_default -select- \& form_submit_default Submit \& form_reset_default Reset .Ve .Sp The \f(CW\*(C`js_\*(C'\fR tags are used in JavaScript alerts, whereas the \f(CW\*(C`form_\*(C'\fR tags are used in \s-1HTML\s0 and templates managed by FormBuilder. .Sp In some of the messages, you will notice a \f(CW%s\fR \f(CW\*(C`printf\*(C'\fR format. This is because these messages will include certain details for you. For example, the \f(CW\*(C`js_invalid_start\*(C'\fR tag will print the number of errors if you include the \f(CW%s\fR format tag. Of course, you this is optional, so if you leave it out then you won't get the number of errors. .Sp The best way to get an idea of how these work is to experiment a little. It should become obvious really quickly. .IP "debug => 0 | 1 | 2" 4 .IX Item "debug => 0 | 1 | 2" If set to 1, the module spits copious debugging info to \s-1STDERR\s0. If set to 2, it spits out even more gunk. Defaults to 0. .Sh "\fIrender()\fP" .IX Subsection "render()" This function renders the form into \s-1HTML\s0, and returns a string containing the form. The most common use is simply: .PP .Vb 1 \& print $form->render; .Ve .PP However, \f(CW\*(C`render()\*(C'\fR accepts \fBthe exact same options\fR as \f(CW\*(C`new()\*(C'\fR Why? Because this allows you to set certain options at different points in your code, which is often useful. For example, you could change the formatting based on whether \f(CW\*(C`layout\*(C'\fR appeared in the query string: .PP .Vb 2 \& my $form = CGI::FormBuilder->new(method => 'POST', \& fields => [qw/name email/]); .Ve .PP .Vb 2 \& # Get our layout from an extra CGI param \& my $layout = $form->cgi_param('layout'); .Ve .PP .Vb 6 \& # If we're using a layout, then make sure to request a template \& if ($layout) { \& print $form->render(template => $layout); \& } else { \& print $form->render(header => 1); \& } .Ve .PP The following are all the options accepted by both \f(CW\*(C`new()\*(C'\fR and \&\f(CW\*(C`render()\*(C'\fR: .ie n .IP "action => $script" 4 .el .IP "action => \f(CW$script\fR" 4 .IX Item "action => $script" What script to point the form to. Defaults to itself, which is the recommended setting. .IP "body => \e%hash" 4 .IX Item "body => %hash" This takes a hashref of attributes that will be stuck in the \&\f(CW\*(C`\*(C'\fR tag verbatim (for example, bgcolor, alink, etc). If you're thinking about using this, also check out the \&\f(CW\*(C`template\*(C'\fR option above (and below). .IP "fieldtype => 'type'" 4 .IX Item "fieldtype => 'type'" This can be used to set the default type for all fields. For example, if you're writing a survey application, you may want all of your fields to be of type \f(CW\*(C`textarea\*(C'\fR by default. Easy: .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(... fieldtype => 'textarea'); .Ve .IP "fieldattr => { opt => val, opt => val }" 4 .IX Item "fieldattr => { opt => val, opt => val }" Even more flexible than \f(CW\*(C`fieldtype\*(C'\fR, this option allows you to specify \fIany\fR type of \s-1HTML\s0 attribute and have it be the default for all fields. For example: .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(... fieldattr => { class => 'myClass' }); .Ve .Sp Would set the \f(CW\*(C`class\*(C'\fR \s-1HTML\s0 attribute on all fields by default, so that when they are printed out they will have a \f(CW\*(C`class="myClass"\*(C'\fR part of their \s-1HTML\s0 tag. Maybe you want a template? .ie n .IP "font => $font | \e%fonttags" 4 .el .IP "font => \f(CW$font\fR | \e%fonttags" 4 .IX Item "font => $font | %fonttags" The font face to use for the form. This is output as a series of \&\f(CW\*(C`\*(C'\fR tags for best browser compatibility, and will even take care of the tedious table elements. I use this option all the time. If you specify a hashref instead of just a font name, then each key/value pair will be taken as part of the \f(CW\*(C`\*(C'\fR tag. For example: .Sp .Vb 1 \& font => {face => 'verdana', size => '-1', color => 'gray'} .Ve .Sp Would generate the following tag: .Sp .Vb 1 \& .Ve .Sp And properly nest them in all of the table elements. .IP "header => 0 | 1" 4 .IX Item "header => 0 | 1" If set to 1, a valid \f(CW\*(C`Content\-type\*(C'\fR header will be printed out, along with a whole bunch of \s-1HTML\s0 \f(CW\*(C`\*(C'\fR code, a \f(CW\*(C`\*(C'\fR tag, and so on. This defaults to 0, since usually people end up using templates or embedding forms in other \s-1HTML\s0. Setting it to 1 is a great way to throw together a quick and dirty form, though. .IP "javascript => 0 | 1" 4 .IX Item "javascript => 0 | 1" If set to 1, JavaScript is generated in addition to \s-1HTML\s0, the default setting. .IP "jshead => \s-1JSCODE\s0" 4 .IX Item "jshead => JSCODE" If using JavaScript, you can also specify some JavaScript code that will be included verbatim in the <head> section of the document. I'm not very fond of this one, what you probably want is the next option. .IP "jsfunc => \s-1JSCODE\s0" 4 .IX Item "jsfunc => JSCODE" Just like \f(CW\*(C`jshead\*(C'\fR, only this is stuff that will go into the \&\f(CW\*(C`validate\*(C'\fR JavaScript function. As such, you can use it to add extra JavaScript validate code verbatim. If something fails, you should do two things: .Sp .Vb 2 \& - append to the JS variable "alertstr" \& - increment the JS variable "invalid" .Ve .Sp For example: .Sp .Vb 6 \& my $jsfunc = <<EOJS; \& if (form.password.value == 'password') { \& alertstr += "Moron, you can't use 'password' for your password!\e\en"; \& invalid++; \& } \& EOJS .Ve .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(... jsfunc => $jsfunc); .Ve .Sp Then, this code will be automatically called when form validation is invoked. I find this option can be incredibly useful. Most often, I use it to bypass validation on certain submit modes. The submit button that was clicked is \f(CW\*(C`form._submit.value\*(C'\fR: .Sp .Vb 9 \& my $jsfunc = <<EOJS; \& if (form._submit.value == 'Delete') { \& if (confirm("Really DELETE this entry?")) return true; \& return false; \& } else if (form._submit.value == 'Cancel') { \& // skip validation since we're cancelling \& return true; \& } \& EOJS .Ve .Sp Important: When you're quoting, remember that Perl will expand \*(L"\en\*(R" itself. So, if you want a literal newline, you must double-escape it, as shown above. .IP "keepextras => 0 | 1 | \e@array" 4 .IX Item "keepextras => 0 | 1 | @array" If set to 1, then extra parameters not set in your fields declaration will be kept as hidden fields in the form. However, you will need to use \f(CW\*(C`cgi_param()\*(C'\fR, not \f(CW\*(C`field()\*(C'\fR, to get to the values. This is useful if you want to keep some extra parameters like referer or company available but not have them be valid form fields. See below under \f(CW\*(C`/"param"\*(C'\fR for more details. .Sp You can also specify an arrayref, in which case only params found on that list will be preserved. For example, saying: .Sp .Vb 1 \& ->new(keepextras => 1, ...); .Ve .Sp Will preserve all non-field parameters, whereas saying: .Sp .Vb 1 \& ->new(keepextras => [qw/mode company/], ...); .Ve .Sp Will only preserve the params \f(CW\*(C`mode\*(C'\fR and \f(CW\*(C`company\*(C'\fR. .IP "labels => \e%hash" 4 .IX Item "labels => %hash" Like \f(CW\*(C`values\*(C'\fR, this is a list of key/value pairs where the keys are the names of \f(CW\*(C`fields\*(C'\fR specified above. By default, \fBFormBuilder\fR does some snazzy case and character conversion to create pretty labels for you. However, if you want to explicitly name your fields, use this option. .Sp For example: .Sp .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => [qw/name email/], \& labels => { \& name => 'Your Full Name', \& email => 'Primary Email Address' \& } \& ); .Ve .Sp Usually you'll find that if you're contemplating this option what you really want is a template. .IP "lalign => 'left' | 'right' | 'center'" 4 .IX Item "lalign => 'left' | 'right' | 'center'" This is how to align the field labels in the table layout. I really don't like this option being here, but it does turn out to be pretty damn useful. You should probably be using a template. .IP "linebreaks => 0 | 1" 4 .IX Item "linebreaks => 0 | 1" If set to 1, line breaks will be inserted after each input field. By default this is figured out for you, so usually not needed. .IP "method => '\s-1POST\s0' | '\s-1GET\s0'" 4 .IX Item "method => 'POST' | 'GET'" Either \f(CW\*(C`POST\*(C'\fR or \f(CW\*(C`GET\*(C'\fR, the type of \s-1CGI\s0 method to use. Defaults to \f(CW\*(C`GET\*(C'\fR if nothing is specified. .IP "options => \e%hash" 4 .IX Item "options => %hash" By using this argument, you can avoid having to specify the options for different fields individually: .Sp .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => [qw/part_number department in_stock/], \& options => { \& department => [qw/hardware software/], \& in_stock => [qw/yes no/], \& } \& ); .Ve .Sp This will then create the appropriate multi-option \s-1HTML\s0 inputs (in this case, radio groups) automatically. .IP "required => \e@array | '\s-1ALL\s0' | '\s-1NONE\s0'" 4 .IX Item "required => @array | 'ALL' | 'NONE'" This is a list of those values that are required to be filled in. Those fields named must be included by the user. If the \f(CW\*(C`required\*(C'\fR option is not specified, by default any fields named in \f(CW\*(C`validate\*(C'\fR will be required. .Sp As of v1.97, the \f(CW\*(C`required\*(C'\fR option now takes two other settings, the string \f(CW\*(C`ALL\*(C'\fR and the string \f(CW\*(C`NONE\*(C'\fR. If you specify \f(CW\*(C`ALL\*(C'\fR, then all fields are required. If you specify \f(CW\*(C`NONE\*(C'\fR, then none of them are \fIin spite of what may be set via the \*(L"validate\*(R" option\fR. .Sp This is useful if you have fields that you need to be validated if filled in, but which are optional. For example: .Sp .Vb 5 \& my $form = CGI::FormBuilder->new( \& fields => qw[/name email/], \& validate => { email => 'EMAIL' }, \& required => 'NONE' \& ); .Ve .Sp This would make the \f(CW\*(C`email\*(C'\fR field optional, but if filled in then it would have to match the \f(CW\*(C`EMAIL\*(C'\fR pattern. .Sp In addition, it is \fIvery\fR important to note that if the \f(CW\*(C`required\*(C'\fR \&\fIand\fR \f(CW\*(C`validate\*(C'\fR options are specified, then they are taken as an intersection. That is, only those fields specified as \f(CW\*(C`required\*(C'\fR must be filled in, and the rest are optional. For example: .Sp .Vb 5 \& my $form = CGI::FormBuilder->new( \& fields => qw[/name email/], \& validate => { email => 'EMAIL' }, \& required => [qw/name/] \& ); .Ve .Sp This would make the \f(CW\*(C`name\*(C'\fR field mandatory, but the \f(CW\*(C`email\*(C'\fR field optional. However, if \f(CW\*(C`email\*(C'\fR is filled in, then it must match the builtin \f(CW\*(C`EMAIL\*(C'\fR pattern. .ie n .IP "reset => 0 | $string" 4 .el .IP "reset => 0 | \f(CW$string\fR" 4 .IX Item "reset => 0 | $string" If set to 0, then the \*(L"Reset\*(R" button is not printed. If set to text, then that will be printed out as the reset button. Defaults to printing out a button that says \*(L"Reset\*(R". .ie n .IP "selectnum => $threshold" 4 .el .IP "selectnum => \f(CW$threshold\fR" 4 .IX Item "selectnum => $threshold" These affect the \*(L"intelligence\*(R" of the module. If a given field has any options, then it will be a radio group by default. However, if more than \f(CW\*(C`selectnum\*(C'\fR options are present, then it will become a select list. The default is 5 or more options. For example: .Sp .Vb 3 \& # This will be a radio group \& my @opt = qw(Yes No); \& $form->field(name => 'answer', options => \e@opt); .Ve .Sp .Vb 3 \& # However, this will be a select list \& my @states = qw(AK CA FL NY TX); \& $form->field(name => 'state', options => \e@states); .Ve .Sp .Vb 2 \& # This is the one special case - single items are checkboxes \& $form->field(name => 'answer', options => ['Yes']); .Ve .Sp There is no threshold for checkboxes since these are basically a type of multiple radio select group. As such, a radio group becomes a checkbox group if there are multiple values (not options, but actual values) for a given field, or if you specify \f(CW\*(C`multiple => 1\*(C'\fR to the \f(CW\*(C`field()\*(C'\fR method. Got it? .IP "smartness => 0 | 1 | 2" 4 .IX Item "smartness => 0 | 1 | 2" By default CGI::FormBuilder tries to be pretty smart for you, like figuring out the types of fields based on their names and number of options. If you don't want this behavior at all, set \f(CW\*(C`smartness\*(C'\fR to \f(CW0\fR. If you want it to be \fBreally\fR smart, like figuring out what type of validation routines to use for you, set it to \&\f(CW2\fR. It defaults to \f(CW1\fR. .IP "sortopts => alpha | numeric | \s-1NAME\s0 | \s-1NUM\s0 | 1" 4 .IX Item "sortopts => alpha | numeric | NAME | NUM | 1" If specified to \f(CW\*(C`render()\*(C'\fR or \f(CW\*(C`new()\*(C'\fR, this has the same effect as the same-named option to \f(CW\*(C`field()\*(C'\fR, only it applies to all fields. .IP "static => 0 | 1" 4 .IX Item "static => 0 | 1" If set to 1, then the form will be output with static hidden fields. Defaults to 0. .IP "sticky => 0 | 1" 4 .IX Item "sticky => 0 | 1" Determines whether or not form values should be sticky across submissions. This does \fInot\fR affect the value you get back from a call to \f(CW\*(C`field()\*(C'\fR. It also does not affect default values. It only affects values the user may have entered via the \s-1CGI\s0. .Sp This defaults to 1, meaning values are sticky. However, you may want to set it to 0 if you have a form which does something like adding parts to a database. See the \*(L"\s-1EXAMPLES\s0\*(R" section for a good example. .ie n .IP "submit => 0 | $string | \e@array" 4 .el .IP "submit => 0 | \f(CW$string\fR | \e@array" 4 .IX Item "submit => 0 | $string | @array" If set to 0, then the \*(L"Submit\*(R" button is not printed. It defaults to creating a button that says \*(L"Submit\*(R" verbatim. If given an argument, then that argument becomes the text to show. For example: .Sp .Vb 1 \& print $form->render(submit => 'Do Lookup'); .Ve .Sp Would make it so the submit button says \*(L"Do Lookup\*(R" on it. .Sp If you pass an arrayref of multiple values, you get a key benefit. This will create multiple submit buttons, each with a different value. In addition, though, when submitted only the one that was clicked will be sent across \s-1CGI\s0 via some JavaScript tricks. So this: .Sp .Vb 1 \& print $form->render(submit => ['Add A Gift', 'No Thank You']); .Ve .Sp Would create two submit buttons. Clicking on either would submit the form, but you would be able to see which one was submitted via the \&\f(CW\*(C`submitted()\*(C'\fR function: .Sp .Vb 1 \& my $clicked = $form->submitted; .Ve .Sp So if the user clicked \*(L"Add A Gift\*(R" then that is what would end up in the variable \f(CW$clicked\fR above. This allows nice conditionality: .Sp .Vb 5 \& if ($form->submitted eq 'Add A Gift') { \& # show the gift selection screen \& } elsif ($form->submitted eq 'No Thank You') \& # just process the form \& } .Ve .Sp See the \*(L"\s-1EXAMPLES\s0\*(R" section for more details. .IP "table => 0 | 1 | \e%tabletags" 4 .IX Item "table => 0 | 1 | %tabletags" By default \fBFormBuilder\fR decides how to layout the form based on the number of fields, values, etc. You can force it into a table by specifying \f(CW1\fR, or force it out of one with \f(CW0\fR. .Sp If you specify a hashref instead, then these will be used to create the \f(CW\*(C`<table>\*(C'\fR tag. For example, to create a table with no cellpadding or cellspacing, use: .Sp .Vb 1 \& table => {cellpadding => 0, cellspacing => 0} .Ve .ie n .IP "template => $filename | \e%hash" 4 .el .IP "template => \f(CW$filename\fR | \e%hash" 4 .IX Item "template => $filename | %hash" This points to a filename that contains an \f(CW\*(C`HTML::Template\*(C'\fR compatible template to use to layout the \s-1HTML\s0. You can also specify the \f(CW\*(C`template\*(C'\fR option as a reference to a hash, allowing you to further customize the template processing options. .Sp For example, you could turn on caching in \f(CW\*(C`HTML::Template\*(C'\fR with something like the following: .Sp .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& filename => 'form.tmpl', \& shared_cache => 1 \& } \& ); .Ve .Sp In addition, specifying a hashref allows you to use an alternate template processing system like the \f(CW\*(C`Template Toolkit\*(C'\fR. A minimal configuration would look like this: .Sp .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'TT2', # use Template Toolkit \& template => 'form.tmpl', \& }, \& ); .Ve .Sp The \f(CW\*(C`type\*(C'\fR option specifies the name of the processor. Use \f(CW\*(C`TT2\*(C'\fR to invoke the Template Toolkit or \f(CW\*(C`HTML\*(C'\fR (the default) to invoke \&\f(CW\*(C`HTML::Template\*(C'\fR as shown above. All other options besides \f(CW\*(C`type\*(C'\fR are passed to the constructor for that templating system verbatim, so you'll need to consult those docs to see what different options do. .Sp For lots more information on templates, see the \*(L"\s-1TEMPLATES\s0\*(R" section below. .ie n .IP "text => $text" 4 .el .IP "text => \f(CW$text\fR" 4 .IX Item "text => $text" This is text that is included below the title but above the actual form. Useful if you want to say something simple like \&\*(L"Contact \f(CW$adm\fR for more help\*(R", but if you want lots of text check out the \f(CW\*(C`template\*(C'\fR option above. .ie n .IP "title => $title" 4 .el .IP "title => \f(CW$title\fR" 4 .IX Item "title => $title" This takes a string to use as the title of the form. .IP "valign => 'top' | 'middle' | 'bottom'" 4 .IX Item "valign => 'top' | 'middle' | 'bottom'" Another one I don't like, this alters how form fields are laid out in the natively-generated table. Default is \*(L"middle\*(R". .IP "values => \e%hash | \e@array" 4 .IX Item "values => %hash | @array" The \f(CW\*(C`values\*(C'\fR option takes a hashref of key/value pairs specifying the default values for the fields. These values will be overridden by the values entered by the user across the \s-1CGI\s0. The values are used case\-insensitively, making it easier to use \s-1DBI\s0 hashref records (which are in upper or lower case depending on your database). .Sp This option is useful for selecting a record from a database or hardwiring some sensible defaults, and then including them in the form so that the user can change them if they wish. For example: .Sp .Vb 3 \& my $rec = $sth->fetchrow_hashref; \& my $form = CGI::FormBuilder->new(fields => \e@fields, \& values => $rec); .Ve .Sp You can also pass an arrayref, in which case each value is used sequentially for each field as specified to the \f(CW\*(C`fields\*(C'\fR option. While \f(CW\*(C`new()\*(C'\fR is used as an example, this can of course be used in \f(CW\*(C`render()\*(C'\fR as well. .PP Note that any other options specified are passed to the \f(CW\*(C`<form>\*(C'\fR tag verbatim. For example, you could specify \f(CW\*(C`onSubmit\*(C'\fR or \f(CW\*(C`enctype\*(C'\fR to add the respective attributes. .Sh "\fIfield()\fP" .IX Subsection "field()" This method is called on the \f(CW$form\fR object you get from the \f(CW\*(C`new()\*(C'\fR method above, and is used to manipulate individual fields. You can use this if you want to specify something is a certain type of input, or has a certain set of options. .PP For example, let's say that you create a new form: .PP .Vb 1 \& my $form = CGI::FormBuilder->new(fields => [qw/name state zip/]); .Ve .PP And that you want to make the \*(L"state\*(R" field a select list of all the states. You would just say: .PP .Vb 2 \& $form->field(name => 'state', type => 'select', \& options => \e@states); .Ve .PP Then, when you used \f(CW\*(C`render()\*(C'\fR to create the form output, the \*(L"state\*(R" field would appear as a select list with the values in \f(CW@states\fR as options. .PP If just given the name of the field, then the value of that field will be returned, just like \f(CW\*(C`CGI.pm\*(C'\fR: .PP .Vb 1 \& my $email = $form->field('email'); .Ve .PP Why is this not named \f(CW\*(C`param()\*(C'\fR? Simple: Because it's not compatible. Namely, while the return context behavior is the same, this function is not responsible for retrieving all \s-1CGI\s0 parameters \- only those defined as valid form fields. This is important, as it allows your script to accept only those field names you've defined for security. .PP To get the list of valid field names just call it without and args: .PP .Vb 1 \& my @fields = $form->field; .Ve .PP And to get a hashref of field/value pairs, call it as: .PP .Vb 2 \& my $fields = $form->field; \& my $name = $fields->{name}; .Ve .PP Note that if you call it as a hashref, you will only get one single value per field. This is just fine as long as you don't have multiple values per field (the normal case). However, if you have a query string like this: .PP .Vb 1 \& favorite_colors.cgi?color=red&color=white&color=blue .Ve .PP Then you will only get one value for \f(CW\*(C`color\*(C'\fR in the hashref. In this case you'll need to access it via \f(CW\*(C`field()\*(C'\fR to get them all: .PP .Vb 1 \& my @colors = $form->field('color'); .Ve .PP The \f(CW\*(C`field()\*(C'\fR function takes several parameters, the first of which is mandatory. The rest are listed in alphabetical order: .PP Finally, you can also take advantage of a new feature and address fields directly by name. This means instead of: .PP .Vb 1 \& my $address = $form->field('address'); .Ve .PP You can say: .PP .Vb 1 \& my $address = $form->address; .Ve .PP This works for setting properties as well: .PP .Vb 2 \& $form->field(name => 'user_id', size => '8', maxlength => '12'); \& $form->user_id(size => '8', maxlength => '12'); .Ve .PP Both of those would do the exact same thing. You will get a fatal error if you try to address an invalid field. .ie n .IP "name => $name" 4 .el .IP "name => \f(CW$name\fR" 4 .IX Item "name => $name" The name of the field to manipulate. The \*(L"name =>\*(R" part is optional if there's only one argument. For example: .Sp .Vb 2 \& my $email = $form->field(name => 'email'); \& my $email = $form->field('email'); # same thing .Ve .Sp However, if you're specifying more than one argument then you must include the \f(CW\*(C`name\*(C'\fR part: .Sp .Vb 1 \& $form->field(name => 'email', size => '40'); .Ve .ie n .IP "comment => $string" 4 .el .IP "comment => \f(CW$string\fR" 4 .IX Item "comment => $string" This prints out the given comment \fIafter\fR the field to fill in, vebatim. For example, if you wanted a field to look like this: .Sp .Vb 1 \& Joke [____________] (keep it clean, please!) .Ve .Sp You would use the following: .Sp .Vb 1 \& $form->field(name => 'joke', comment => '(keep it clean, please!)'); .Ve .Sp The \f(CW\*(C`comment\*(C'\fR can actually be anything you want (even another form field). But don't tell anyone I said that. .IP "force => 0 | 1" 4 .IX Item "force => 0 | 1" This is used in conjunction with the \f(CW\*(C`value\*(C'\fR option to forcibly override a field's value. See below under the \f(CW\*(C`value\*(C'\fR option for more details. For compatibility with \f(CW\*(C`CGI.pm\*(C'\fR, you can also call this option \f(CW\*(C`override\*(C'\fR instead, but don't tell anyone. .ie n .IP "jsclick => $jscode" 4 .el .IP "jsclick => \f(CW$jscode\fR" 4 .IX Item "jsclick => $jscode" This is a simple abstraction over directly specifying the JavaScript action type. This turns out to be extremely useful, since if an option list changes from \f(CW\*(C`select\*(C'\fR to \f(CW\*(C`radio\*(C'\fR or \f(CW\*(C`checkbox\*(C'\fR (depending on the number of options), then the action changes from \f(CW\*(C`onChange\*(C'\fR to \f(CW\*(C`onClick\*(C'\fR. Why?!?! .Sp So if you said: .Sp .Vb 2 \& $form->field(name => 'credit_card', jsclick => 'recalc_total();', \& options => \e@cards) .Ve .Sp This would generate the following code, depending on the number of \f(CW@cards\fR: .Sp .Vb 1 \& <select name="credit_card" onChange="recalc_total();"> ... .Ve .Sp .Vb 1 \& <radio name="credit_card" onClick="recalc_total();"> ... .Ve .Sp You get the idea. .ie n .IP "label => $string" 4 .el .IP "label => \f(CW$string\fR" 4 .IX Item "label => $string" This will be the label printed out next to the field. By default it will be generated automatically from the field name. .IP "labels => \e%hash" 4 .IX Item "labels => %hash" This takes a hashref of key/value pairs where each key is one of the options, and each value is what its printed label should be. For example: .Sp .Vb 8 \& $form->field(name => 'state', options => [qw/AZ CA NV OR WA/], \& labels => { \& AZ => 'Arizona', \& CA => 'California', \& NV => 'Nevada', \& OR => 'Oregon', \& WA => 'Washington \& }); .Ve .Sp When rendered, this would create a select list where the option values were \*(L"\s-1CA\s0\*(R", \*(L"\s-1NV\s0\*(R", etc, but where the state's full name was displayed for the user to select. .Sp You can also get the same effect by passing complex data structures directly to the \f(CW\*(C`options\*(C'\fR argument (see below). If you have predictable data, check out the \f(CW\*(C`nameopts\*(C'\fR option. .IP "linebreaks => 0 | 1" 4 .IX Item "linebreaks => 0 | 1" Similar to the top-level \*(L"linebreaks\*(R" option, this one will put breaks in between options, to space things out more. This is useful with radio and checkboxes especially. .IP "multiple => 0 | 1" 4 .IX Item "multiple => 0 | 1" If set to 1, then the user is allowed to choose multiple values from the options provided. This turns radio groups into checkboxes and selects into multi\-selects. Defaults to automatically being figured out based on number of values. .IP "nameopts => 0 | 1" 4 .IX Item "nameopts => 0 | 1" If set to 1, then options for select lists will be automatically named just like the fields. So, if you specified a list like: .Sp .Vb 4 \& $form->field(name => 'department', \& options => qw[/molecular_biology philosophy psychology \& particle_physics social_anthropology/], \& nameopts => 1); .Ve .Sp This would create a list like: .Sp .Vb 7 \& <select name="department"> \& <option value="molecular_biology">Molecular Biology</option> \& <option value="philosophy">Philosophy</option> \& <option value="psychology">Psychology</option> \& <option value="particle_physics">Particle Physics</option> \& <option value="social_anthropology">Social Anthropology</option> \& </select> .Ve .Sp Basically, you get names for the options that are determined in the same way as the names for the fields. This is designed as a simpler alternative to using custom \f(CW\*(C`options\*(C'\fR data structures if your data is regular enough to support it. .IP "options => \e@options | \e%options | '\s-1BUILTIN\s0'" 4 .IX Item "options => @options | %options | 'BUILTIN'" This takes an arrayref of options. It also automatically results in the field becoming a radio (if <= 4) or select list (if > 4), unless you explicitly set the type with the \f(CW\*(C`type\*(C'\fR parameter. .Sp Each item will become both the value and the text label by default. That is, if you specified these options: .Sp .Vb 1 \& $form->field(name => 'opinion', options => [qw/yes no maybe so/]); .Ve .Sp You will get something like this: .Sp .Vb 6 \& <select name="opinion"> \& <option value="yes">yes</option> \& <option value="no">no</option> \& <option value="maybe">maybe</option> \& <option value="so">so</option> \& </select> .Ve .Sp However, if a given item is either an arrayref or hashref, then the first element will be taken as the value and the second as the label. So something like this: .Sp .Vb 5 \& push @opt, ['yes', 'You betcha!']; \& push @opt, ['no', 'No way Jose']; \& push @opt, ['maybe', 'Perchance...']; \& push @opt, ['so', 'So']; \& $form->field(name => 'opinion', options => \e@opt); .Ve .Sp Would result in something like the following: .Sp .Vb 6 \& <select name="opinion"> \& <option value="yes">You betcha!</option> \& <option value="no">No way Jose</option> \& <option value="maybe">Perchance...</option> \& <option value="so">So</option> \& </select> .Ve .Sp And this code would have the same effect: .Sp .Vb 5 \& push @opt, { yes => 'You betcha!' }; \& push @opt, { no => 'No way Jose' }; \& push @opt, { maybe => 'Perchance...' }; \& push @opt, { so => 'So' }; \& $form->field(name => 'opinion', options => \e@opt); .Ve .Sp As would, in fact, this code: .Sp .Vb 7 \& my %opt = ( \& yes => 'You betcha!', \& no => 'No way Jose', \& maybe => 'Perchance...', \& so => 'So' \& ); \& $form->field(name => 'opinion', options => \e%opt); .Ve .Sp You get the idea. The goal is to give you as much flexibility as possible when constructing your data structures, and this module figures it out correctly. The only disadvantage to the very last method is that since the top-level structure is a hash, you cannot control the order of the options. .Sp If you're just looking for simple naming, see the \f(CW\*(C`nameopts\*(C'\fR option above. .Sp Finally, currently a single builtin options set is included: \&\f(CW\*(C`STATE\*(C'\fR, which contains all 50 states + \s-1DC\s0 as 2\-letter codes. .IP "override => 0 | 1" 4 .IX Item "override => 0 | 1" A synonym for the \f(CW\*(C`force\*(C'\fR option described above. .IP "required => 0 | 1" 4 .IX Item "required => 0 | 1" If set to 1, the field must be filled in: .Sp .Vb 1 \& $form->field(name => 'email', required => 1); .Ve .Sp This is rarely useful \- what you probably want is the \f(CW\*(C`validate\*(C'\fR option to \f(CW\*(C`new()\*(C'\fR. .IP "sortopts => alpha | numeric | \s-1NAME\s0 | \s-1NUM\s0 | 1" 4 .IX Item "sortopts => alpha | numeric | NAME | NUM | 1" If set, and there are options, then the options will be sorted in the specified order. For example: .Sp .Vb 2 \& $form->field(name => 'category', options => \e@cats, \& sortopts => 'alpha'); .Ve .Sp Would sort the \f(CW@cats\fR options in alpha order. .Sp The terms \*(L"\s-1NAME\s0\*(R" and \*(L"\s-1NUM\s0\*(R" have been introduced to keep consistency with the \f(CW\*(C`validate\*(C'\fR options. They are synonymous with \*(L"alpha\*(R" and \&\*(L"numeric\*(R", respectively. If you specify \*(L"1\*(R", then an alpha sort is done, again for simplicity. .ie n .IP "type => $type" 4 .el .IP "type => \f(CW$type\fR" 4 .IX Item "type => $type" Type of input box to make it. Default is \*(L"text\*(R", and valid values include anything allowed by the \s-1HTML\s0 specs, including \*(L"password\*(R", \&\*(L"select\*(R", \*(L"radio\*(R", \*(L"checkbox\*(R", \*(L"textarea\*(R", \*(L"hidden\*(R", and so on. .Sp If set to \*(L"static\*(R", then the field will be printed out, but will not be editable. Like when you print out a complete static form, the field's value will be placed in a hidden field as well. .ie n .IP "value => $value | \e@values" 4 .el .IP "value => \f(CW$value\fR | \e@values" 4 .IX Item "value => $value | @values" The \f(CW\*(C`value\*(C'\fR option can take either a single value or an arrayref of multiple values. In the case of multiple values, this will result in the field automatically becoming a multiple select list or checkbox group, depending on the number of options specified above. .Sp Just like the 'values' to \f(CW\*(C`new()\*(C'\fR, this can be overridden by \&\s-1CGI\s0 values. To forcibly change a value, you need to specify the \&\f(CW\*(C`force\*(C'\fR option described above, for example: .Sp .Vb 2 \& $form->field(name => 'credit_card', value => 'not shown', \& force => 1); .Ve .Sp This would make the \f(CW\*(C`credit_card\*(C'\fR field into \*(L"not shown\*(R", useful for hiding stuff if you're going to use \f(CW\*(C`mailresults()\*(C'\fR. .IP "validate => '/regex/'" 4 .IX Item "validate => '/regex/'" Similar to the \f(CW\*(C`validate\*(C'\fR option used in \f(CW\*(C`new()\*(C'\fR, this affects the validation just of that single field. As such, rather than a hashref, you would just specify the regex to match against. .Sp \&\fBThis regex must be specified as a single-quoted string, and \&\s-1NOT\s0 as a \f(BIqr()\fB regex\fR. The reason is that this needs to be easily usable by JavaScript routines as well. .ie n .IP "[htmlattr] => $value\fR, [htmlattr] => \f(CW$value" 4 .el .IP "[htmlattr] => \f(CW$value\fR, [htmlattr] => \f(CW$value\fR" 4 .IX Item "[htmlattr] => $value, [htmlattr] => $value" In addition to the above tags, the \f(CW\*(C`field()\*(C'\fR function can take any other valid \s-1HTML\s0 attribute, which will be placed in the tag verbatim. For example, if you wanted to alter the class of the field (if you're using stylesheets and a template, for example), you could say: .Sp .Vb 2 \& $form->field(name => 'email', class => 'FormField', \& size => 80); .Ve .Sp Then when you call \f(CW\*(C`$form\-\*(C'\fRrender> you would get a field something like this: .Sp .Vb 1 \& <input type="text" name="email" class="FormField" size="80"> .Ve .Sp (Of course, for this to really work you still have to create a class called \f(CW\*(C`FormField\*(C'\fR in your stylesheet.) .Sp See also the \f(CW\*(C`fieldattr\*(C'\fR option which can be passed to either \&\f(CW\*(C`new()\*(C'\fR or \f(CW\*(C`render()\*(C'\fR and which provides global defaults for all fields. .Sh "\fIcgi_param()\fP" .IX Subsection "cgi_param()" Wait a second, if we have \f(CW\*(C`field()\*(C'\fR from above, why the heck would we ever need \f(CW\*(C`cgi_param()\*(C'\fR? .PP Simple. The above \f(CW\*(C`field()\*(C'\fR function does a bunch of special stuff. For one thing, it will only return fields which you have explicitly defined in your form. Excess parameters will be silently ignored. Also, it will incorporate defaults you give it, meaning you may get a value back even though the user didn't enter one explicitly in the form (see above). .PP But, you may have some times when you want extra stuff so that you can maintain state, but you don't want it to appear in your form. B2B and branding are easy examples: .PP .Vb 1 \& http://hr-outsourcing.com/newuser.cgi?company=mr_propane .Ve .PP This could change stuff in your form so that it showed the logo and company name for the appropriate vendor, without polluting your form parameters. .PP This call simply redispatches to \f(CW\*(C`CGI::Minimal\*(C'\fR (if installed) or \f(CW\*(C`CGI.pm\*(C'\fR's \f(CW\*(C`param()\*(C'\fR methods, so consult those docs for more information. .Sh "\fItmpl_param()\fP" .IX Subsection "tmpl_param()" This allows you to interface with your \f(CW\*(C`HTML::Template\*(C'\fR template, if you are using one. As with \f(CW\*(C`cgi_param()\*(C'\fR above, this is only useful if you're manually setting non-field values. \fBFormBuilder\fR will automatically setup your field parameters for you; see the \&\*(L"template\*(R" option for more details. .Sh "\fIconfirm()\fP" .IX Subsection "confirm()" The purpose of this function is to print out a static confirmation screen showing a short message along with the values that were submitted. It is actually just a special wrapper around \f(CW\*(C`render()\*(C'\fR, twiddling a couple options. .PP If you're using templates, you probably want to specify a separate success template, such as: .PP .Vb 1 \& print $form->confirm(template => 'success.tmpl'); .Ve .PP So that you don't get the same screen twice. .Sh "\fIsubmitted()\fP" .IX Subsection "submitted()" This returns the value of the \*(L"Submit\*(R" button if the form has been submitted, undef otherwise. This allows you to either test it in a boolean context: .PP .Vb 1 \& if ($form->submitted) { ... } .Ve .PP Or to retrieve the button that was actually clicked on in the case of multiple submit buttons: .PP .Vb 5 \& if ($form->submitted eq 'Update') { \& ... \& } elsif ($form->submitted eq 'Delete') { \& ... \& } .Ve .PP It's best to call \f(CW\*(C`validate()\*(C'\fR in conjunction with this to make sure the form validation works. To make sure you're getting accurate info, it's recommended that you name your forms with the \f(CW\*(C`name\*(C'\fR option described above. .PP If you're writing a multiple-form app, you should name your forms with the \f(CW\*(C`name\*(C'\fR option to ensure that you are getting an accurate return value from this sub. See the \f(CW\*(C`name\*(C'\fR option above, under \&\f(CW\*(C`render()\*(C'\fR. .PP You can also specify the name of an optional field which you want to \&\*(L"watch\*(R" instead of the default \f(CW\*(C`_submitted\*(C'\fR hidden field. This is useful if you have a search form and also want to be able to link to it from other documents directly, such as: .PP .Vb 1 \& mysearch.cgi?lookup=what+to+look+for .Ve .PP Normally, \f(CW\*(C`submitted()\*(C'\fR would return false since the \f(CW\*(C`_submitted\*(C'\fR field is not included. However, you can override this by saying: .PP .Vb 1 \& $form->submitted('lookup'); .Ve .PP Then, if the lookup field is present, you'll get a true value. (Actually, you'll still get the value of the \*(L"Submit\*(R" button if present.) .Sh "\fIvalidate()\fP" .IX Subsection "validate()" This validates the form based on the validation criteria passed into \f(CW\*(C`new()\*(C'\fR via the \f(CW\*(C`validate\*(C'\fR option. In addition, you can specify additional criteria to check that will be valid for just that call of \f(CW\*(C`validate()\*(C'\fR. This is useful is you have to deal with different geos: .PP .Vb 5 \& if ($location eq 'US') { \& $form->validate(state => 'STATE', zipcode => 'ZIPCODE'); \& } else { \& $form->validate(state => '/^\ew{2,3}$/'); \& } .Ve .PP Note that if you pass args to your \f(CW\*(C`validate()\*(C'\fR function like this, you will not get JavaScript generated or required fields placed in bold. So, this is good for conditional validation like the above example, but for most applications you want to pass your validation requirements in via the \f(CW\*(C`validate\*(C'\fR option to the \f(CW\*(C`new()\*(C'\fR function, and just call the \f(CW\*(C`validate()\*(C'\fR function with no arguments. .Sh "\fIsessionid()\fP" .IX Subsection "sessionid()" This gets and sets the sessionid, which is stored in the special form field \f(CW\*(C`_sessionid\*(C'\fR. By default no session ids are generated or used. Rather, this is intended to provide a hook for you to easily integrate this with a session id module like \f(CW\*(C`Apache::Session\*(C'\fR. .PP Since you can set the session id via the \f(CW\*(C`_sessionid\*(C'\fR field, you can pass it as an argument when first showing the form: .PP .Vb 1 \& http://mydomain.com/forms/update_info.cgi?_sessionid=0123-091231 .Ve .PP This would set things up so that if you called: .PP .Vb 1 \& my $id = $form->sessionid; .Ve .PP This would get the value \f(CW\*(C`0123\-091231\*(C'\fR in your script. Conversely, if you generate a new sessionid on your own, and wish to include it automatically, simply set is as follows: .PP .Vb 1 \& $form->sessionid($id); .Ve .PP This will cause it to be automatically carried through subsequent forms. .Sh "\fImailconfirm()\fP" .IX Subsection "mailconfirm()" This sends a confirmation email to the named addresses. The \f(CW\*(C`to\*(C'\fR argument is required; everything else is optional. If no \f(CW\*(C`from\*(C'\fR is specified then it will be set to the address \f(CW\*(C`auto\-reply\*(C'\fR since that is a common quasi-standard in the web app world. .PP This does not send any of the form results. Rather, it simply prints out a message saying the submission was received. .Sh "\fImailresults()\fP" .IX Subsection "mailresults()" This emails the form results to the specified address(es). By default it prints out the form results separated by a colon, such as: .PP .Vb 3 \& name: Nathan Wiger \& email: nate@wiger.org \& colors: red green blue .Ve .PP And so on. You can change this by specifying the \f(CW\*(C`delimiter\*(C'\fR and \&\f(CW\*(C`joiner\*(C'\fR options. For example this: .PP .Vb 1 \& $form->mailresults(to => $to, delimiter => '=', joiner => ','); .Ve .PP Would produce an email like this: .PP .Vb 3 \& name=Nathan Wiger \& email=nate@wiger.org \& colors=red,green,blue .Ve .PP Note that now the last field (\*(L"colors\*(R") is separated by commas since you have multiple values and you specified a comma as your \f(CW\*(C`joiner\*(C'\fR. .Sh "\fImail()\fP" .IX Subsection "mail()" This is a more generic version of the above; it sends whatever is given as the \f(CW\*(C`text\*(C'\fR argument via email verbatim to the \f(CW\*(C`to\*(C'\fR address. In addition, if you're not running \f(CW\*(C`sendmail\*(C'\fR you can specify the \&\f(CW\*(C`mailer\*(C'\fR parameter to give the path of your mailer. This option is accepted by the above functions as well. .SH "TEMPLATES" .IX Header "TEMPLATES" \&\fBFormBuilder\fR has the ability to \*(L"drive\*(R" several template engines: .PP .Vb 3 \& HTML::Template \& Text::Template \& Template Toolkit .Ve .PP You enable a template by specifying the \f(CW\*(C`template\*(C'\fR option and passing it the appropriate information. Then, you must place special tags in your template which will be expanded for you. Let's look at each template solution in turn. .Sh "HTML::Template" .IX Subsection "HTML::Template" \&\f(CW\*(C`HTML::Template\*(C'\fR is the default template option and is activated one of two ways. Either: .PP .Vb 4 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => $filename \& ); .Ve .PP Or, you can specify any options which \f(CW\*(C`HTML::Template\->new\*(C'\fR accepts by using a hashref: .PP .Vb 9 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& filename => $filename, \& die_on_bad_params => 0, \& shared_cache => 1, \& loop_context_vars => 1 \& } \& ); .Ve .PP In your template, each of the form fields will correspond directly to a \f(CW\*(C`<tmpl_var>\*(C'\fR of the same name prefixed with \*(L"field\-\*(R" in the template. So, if you defined a field called \*(L"email\*(R", then you would setup a variable called \f(CW\*(C`<tmpl_var field\-email>\*(C'\fR in your template, and this would be expanded to the complete \s-1HTML\s0 \f(CW\*(C`<input>\*(C'\fR tag. .PP In addition, there are a couple special fields: .PP .Vb 6 \& <tmpl_var js-head> - JavaScript to stick in <head> \& <tmpl_var form-title> - The <title> of the HTML form \& <tmpl_var form-start> - Opening <form> tag w/ options \& <tmpl_var form-submit> - The submit button(s) \& <tmpl_var form-reset> - The reset button \& <tmpl_var form-end> - Just the closing </form> tag .Ve .PP So, let's revisit our \f(CW\*(C`userinfo.tmpl\*(C'\fR template from above: .PP .Vb 17 \& <html> \& <head> \& <title>User Information \& \& \& \&

User Information

\& Please fill out the following information: \& \&

Your full name: \&

Your email address: \&

Choose a password: \&

Please confirm it: \&

Your home zipcode: \&

\& \& .Ve .PP As you see, you get a \f(CW\*(C`\*(C'\fR for each for field you define. .PP However, you may want even more control. That is, maybe you want to specify every nitty-gritty detail of your input fields, and just want this module to take care of the statefulness of the values. This is no problem, since this module also provides several other \f(CW\*(C`\*(C'\fR tags as well: .PP .Vb 4 \& - The value of a given field \& - The human-readable label \& - Any optional comment \& - Error text if validation fails .Ve .PP This means you could say something like this in your template: .PP .Vb 3 \& : \& \& .Ve .PP And \fBFormBuilder\fR would take care of the value stickiness for you, while you have control over the specifics of the \f(CW\*(C`\*(C'\fR tag. A sample expansion may create \s-1HTML\s0 like the following: .PP .Vb 3 \& Email: \& \& You must enter a valid value .Ve .PP Note, though, that this will only get the \fIfirst\fR value in the case of a multi-value parameter (for example, a multi-select list). To remedy this, if there are multiple values you will also get a \&\f(CW\*(C`\*(C'\fR prefixed with \*(L"loop\-\*(R". So, if you had: .PP .Vb 1 \& myapp.cgi?color=gray&color=red&color=blue .Ve .PP This would give the \f(CW\*(C`color\*(C'\fR field three values. To create a select list, you would do this in your template: .PP .Vb 5 \& .Ve .PP With \f(CW\*(C`\*(C'\fR tags, each iteration gives you several variables: .PP .Vb 6 \& Inside , this... Gives you this \& --------------------------- ------------------------------- \& value of that option \& label for that option \& if selected, the word "checked" \& if selected, the word "selected" .Ve .PP Please note that \f(CW\*(C`\*(C'\fR gives you one of the \fIoptions\fR, not the values. Why? Well, if you think about it you'll realize that select lists and radio groups are fundamentally different from input boxes in a number of ways. Whereas in input tags you can just have an empty value, with lists you need to iterate through each option and then decide if it's selected or not. .PP When you need precise control in a template this is all exposed to you; normally \fBFormBuilder\fR does all this magic for you. If you don't need exact control over your lists, simply use the \f(CW\*(C`\*(C'\fR tag and this will all be done automatically, which I strongly recommend. .PP But, let's assume you need exact control over your lists. Here's an example select list template: .PP .Vb 5 \& .Ve .PP Then, your Perl code would fiddle the field as follows: .PP .Vb 2 \& $form->field(name => 'color', nameopts => 1, \& options => [qw/red green blue yellow black white gray/]); .Ve .PP Assuming query string as shown above, the template would then be expanded to something like this: .PP .Vb 9 \& .Ve .PP Notice that the \f(CW\*(C`\*(C'\fR tag is expanded to the word \&\*(L"selected\*(R" when a given option is present as a value as well (i.e., via the \s-1CGI\s0 query). The \f(CW\*(C`\*(C'\fR tag expands to each option in turn, and \f(CW\*(C`\*(C'\fR is expanded to the label for that value. In this case, since \f(CW\*(C`nameopts\*(C'\fR was specified to \f(CW\*(C`field()\*(C'\fR, the labels are automatically generated from the options. .PP Let's look at one last example. Here we want a radio group that allows a person to remove themself from a mailing list. Here's our template: .PP .Vb 9 \& Do you want to be on our mailing list? \&

\& \& \& \& \&
\& \&
.Ve .PP Then, we would twiddle our \f(CW\*(C`mailopt\*(C'\fR field via \f(CW\*(C`field()\*(C'\fR: .PP .Vb 5 \& $form->field(name => 'mailopt', options => [qw/1 0/], \& labels => { \& 1 => 'Yes, please keep me on it!', \& 0 => 'No, remove me immediately.' \& }); .Ve .PP When the template is rendered, the result would be something like this: .PP .Vb 2 \& Do you want to be on our mailing list? \&

.Ve .PP .Vb 4 \& \& .Ve .PP .Vb 4 \& \& .Ve .PP .Vb 1 \&
\& \& Yes, please keep me on it! \& \& No, remove me immediately
.Ve .PP When the form was then sumbmitted, you would access the values just like any other field: .PP .Vb 5 \& if ($form->field('mailopt')) { \& # is 1, so add them \& } else { \& # is 0, remove them \& } .Ve .PP Finally, you can also loop through each of the fields using the top-level \&\f(CW\*(C`fields\*(C'\fR loop in your template. This allows you to reuse the same template even if your parameters change. The following template code would loop through each field, creating a table row for each: .PP .Vb 8 \& \& \& \& \& \& \& \&
.Ve .PP Each loop will have a \f(CW\*(C`label\*(C'\fR, \f(CW\*(C`field\*(C'\fR, \f(CW\*(C`value\*(C'\fR, etc, just like above. .PP For more information on templates, see HTML::Template. .Sh "Template Toolkit" .IX Subsection "Template Toolkit" Thanks to a huge patch from Andy Wardley, \fBFormBuilder\fR also supports \&\f(CW\*(C`Template Toolkit\*(C'\fR. This is enabled by specifying the following options as a hashref to the \f(CW\*(C`template\*(C'\fR argument: .PP .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'TT2', # use Template Toolkit \& template => 'form.tmpl' \& } \& ); .Ve .PP By default, the Template Toolkit makes all the form and field information accessible through simple variables. .PP .Vb 8 \& [% jshead %] - JavaScript to stick in \& [% title %] - The of the HTML form \& [% start %] - Opening <form> tag w/ options \& [% submit %] - The submit button(s) \& [% reset %] - The reset button \& [% end %] - Closing </form> tag \& [% fields %] - List of fields \& [% field %] - Hash of fields (for lookup by name) .Ve .PP You can specify the \f(CW\*(C`variable\*(C'\fR option to have all these variables accessible under a certain namespace. For example: .PP .Vb 8 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'TT2', \& template => 'form.tmpl', \& variable => 'form' \& }, \& ); .Ve .PP With \f(CW\*(C`variable\*(C'\fR set to \f(CW\*(C`form\*(C'\fR the variables are accessible as: .PP .Vb 3 \& [% form.jshead %] \& [% form.start %] \& etc. .Ve .PP You can access individual fields via the \f(CW\*(C`field\*(C'\fR variable. .PP .Vb 5 \& For a field named... The field data is in... \& -------------------- ----------------------- \& job [% form.field.job %] \& size [% form.field.size %] \& email [% form.field.email %] .Ve .PP Each field contains various elements. For example: .PP .Vb 1 \& [% myfield = form.field.email %] .Ve .PP .Vb 8 \& [% myfield.label %] # text label \& [% myfield.field %] # field input tag \& [% myfield.value %] # first value \& [% myfield.values %] # list of all values \& [% myfield.option %] # first value \& [% myfield.options %] # list of all values \& [% myfield.required %] # required flag \& [% myfield.invalid %] # invalid flag .Ve .PP The \f(CW\*(C`fields\*(C'\fR variable contains a list of all the fields in the form. To iterate through all the fields in order, you could do something like this: .PP .Vb 5 \& [% FOREACH field = form.fields %] \& <tr> \& <td>[% field.label %]</td> <td>[% field.field %]</td> \& </tr> \& [% END %] .Ve .PP If you want to customise any of the Template Toolkit options, you can set the \f(CW\*(C`engine\*(C'\fR option to contain a reference to an existing \&\f(CW\*(C`Template\*(C'\fR object or hash reference of options which are passed to the \f(CW\*(C`Template\*(C'\fR constructor. You can also set the \f(CW\*(C`data\*(C'\fR item to define any additional variables you want accesible when the template is processed. .PP .Vb 15 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'TT2', \& template => 'form.tmpl', \& variable => 'form' \& engine => { \& INCLUDE_PATH => '/usr/local/tt2/templates', \& }, \& data => { \& version => 1.23, \& author => 'Fred Smith', \& }, \& }, \& ); .Ve .PP For further details on using the Template Toolkit, see \f(CW\*(C`Template\*(C'\fR or www.template\-toolkit.org .Sh "Text::Template" .IX Subsection "Text::Template" Also thanks to a user contribution, this time by Jonathan Buhacoff, \&\f(CW\*(C`Text::Template\*(C'\fR is also supported. Usage is very similar to Template Toolkit: .PP .Vb 7 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'Text', # use Text::Template \& template => 'form.tmpl', \& } \& ); .Ve .PP The default options passed into \f(CW\*(C`Text::Template\-\*(C'\fR\fInew()\fR> with this calling form are: .PP .Vb 3 \& TYPE => 'FILE' \& SOURCE => 'form.tmpl' \& DELIMITERS => ['<%','%>'] .Ve .PP As these params are passed for you, your template will look very similar to ones used by Template Toolkit and \f(CW\*(C`HTML::Mason\*(C'\fR (the Text::Template default delimiters are \f(CW\*(C`{\*(C'\fR and \f(CW\*(C`}\*(C'\fR, but using alternative delimiters speeds it up by about 25%, and the \f(CW\*(C`<%\*(C'\fR and \f(CW\*(C`%>\*(C'\fR delimiters are good, familiar-looking alternatives). .PP .Vb 8 \& <% $jshead %> - JavaScript to stick in <head> \& <% $title %> - The <title> of the HTML form \& <% $start %> - Opening <form> tag w/ options \& <% $submit %> - The submit button(s) \& <% $reset %> - The reset button \& <% $end %> - Closing </form> tag \& <% $fields %> - List of fields \& <% $field %> - Hash of fields (for lookup by name) .Ve .PP Note that you refer to variables with a preceding \f(CW\*(C`$\*(C'\fR, just like in Perl. Like Template Toolkit, you can specify a variable to place fields under: .PP .Vb 8 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'Text', \& template => 'form.tmpl', \& variable => 'form' \& }, \& ); .Ve .PP Unlike Template Toolkit, though, these will not be placed in OO\-style, dot-separated vars. Instead, a hash will be created which you then reference: .PP .Vb 3 \& <% $form{jshead} %> \& <% $form{start} %> \& etc. .Ve .PP And field data is in a hash-of-hashrefs format: .PP .Vb 5 \& For a field named... The field data is in... \& -------------------- ----------------------- \& job <% $form{field}{job} %] \& size <% $form{field}{size} %] \& email <% $form{field}{email} %] .Ve .PP Since \f(CW\*(C`Text::Template\*(C'\fR looks so much like Perl, you can access individual elements and create variables like so: .PP .Vb 11 \& <% \& my $myfield = $form{field}{email}; \& $myfield->{label}; # text label \& $myfield->{field}; # field input tag \& $myfield->{value}; # first value \& $myfield->{values}; # list of all values \& $myfield->{option}; # first option \& $myfield->{options}; # list of all options \& $myfield->{required}; # required flag \& $myfield->{invalid}; # invalid flag \& %> .Ve .PP .Vb 5 \& <% \& for my $field (@{$form{fields}}) { \& $OUT .= "<tr>\en<td>" . $field->{label} . "</td> <td>" . $field->{field} . "</td>\en<tr>"; \& } \& %> .Ve .PP In addition, when using the engine option, as in Template Toolkit, you can supply an existing Text::Template object or a hash of parameters to be passed to \f(CW\*(C`new()\*(C'\fR. For example, you can ask for different delimiters yourself: .PP .Vb 15 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'Text', \& template => 'form.tmpl', \& variable => 'form', \& engine => { \& DELIMITERS => [ '[@--', '--@]' ], \& }, \& data => { \& version => 1.23, \& author => 'Fred Smith', \& }, \& }, \& ); .Ve .PP If you pass a hash of parameters, you can override the \f(CW\*(C`TYPE\*(C'\fR and \f(CW\*(C`SOURCE\*(C'\fR parameters, as well as any other \f(CW\*(C`Text::Template\*(C'\fR options. For example, you can pass in a string template with \f(CW\*(C`TYPE => STRING\*(C'\fR instead of loading it from a file. You must specify \fBboth\fR \f(CW\*(C`TYPE\*(C'\fR and \f(CW\*(C`SOURCE\*(C'\fR if doing so. The good news is this is trivial: .PP .Vb 16 \& my $form = CGI::FormBuilder->new( \& fields => \e@fields, \& template => { \& type => 'Text', \& variable => 'form', \& engine => { \& TYPE => 'STRING', \& SOURCE => $string, \& DELIMITERS => [ '[@--', '--@]' ], \& }, \& data => { \& version => 1.23, \& author => 'Fred Smith', \& }, \& }, \& ); .Ve .PP If you get the crazy idea to let users of your application pick the template file (strongly discouraged) and you're getting errors, look at the \f(CW\*(C`Text::Template\*(C'\fR documentation for the \f(CW\*(C`UNTAINT\*(C'\fR feature. .PP Also, note that \f(CW\*(C`Text::Template\*(C'\fR's \f(CW\*(C`PREPEND => 'use strict;'\*(C'\fR option is not recommended due to the dynamic nature for \f(CW\*(C`FormBuilder\*(C'\fR. If you use it, then you'll have to declare each variable that \f(CW\*(C`FormBuilder\*(C'\fR puts into your template with \&\f(CW\*(C`use vars qw($jshead' ... etc);\*(C'\fR .PP If you're really stuck on this, though, a workaround is to say: .PP .Vb 1 \& PREPEND => 'use strict; use vars qw(%form);' .Ve .PP and then set the option \f(CW\*(C`variable => 'form'\*(C'\fR. That way you can have strict Perl without too much hassle, except that your code might be exhausting to look at :\-). Things like \f(CW$form{field}{your_field_name}{field}\fR end up being all over the place, instead of the nicer short forms. .PP Finally, when you use the \f(CW\*(C`data\*(C'\fR template option, the keys you specify will be available to the template as regular variables. In the above example, these would be \&\f(CW\*(C`<% $version %>\*(C'\fR and \f(CW\*(C`<% $author %>\*(C'\fR. And complex datatypes are easy: .PP .Vb 4 \& data => { \& anArray => [ 1, 2, 3 ], \& aHash => { orange => 'tangy', chocolate => 'sweet' }, \& } .Ve .PP This becomes the following in your template: .PP .Vb 4 \& <% \& @anArray; # you can use $myArray[1] etc. \& %aHash; # you can use $myHash{chocolate} etc. \& %> .Ve .PP For more information, please consult the \f(CW\*(C`Text::Template\*(C'\fR documentation. .SH "EXAMPLES" .IX Header "EXAMPLES" I find this module incredibly useful, so here are even more examples, pasted from sample code that I've written: .Sh "Ex1: order.cgi" .IX Subsection "Ex1: order.cgi" This example provides an order form complete with validation of the important fields. .PP .Vb 1 \& #!/usr/bin/perl -w .Ve .PP .Vb 2 \& use strict; \& use CGI::FormBuilder; .Ve .PP .Vb 3 \& my @states = qw(AL AK AZ AR CA CO CT DE DC FL GE HI ID IL IN IA KS \& KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC \& ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY); .Ve .PP .Vb 7 \& my $form = CGI::FormBuilder->new( \& header => 1, method => 'POST', title => 'Order Info', \& fields => [qw/first_name last_name email address \& state zipcode credit_card/], \& validate => {email => 'EMAIL', zipcode => 'ZIPCODE', \& credit_card => 'CARD'} \& ); .Ve .PP .Vb 1 \& $form->field(name => 'state', options => \e@states, sort => 'alpha'); .Ve .PP .Vb 2 \& # This adds on the 'details' field to our form dynamically \& $form->field(name => 'details', cols => '50', rows => '10'); .Ve .PP .Vb 7 \& # try to validate it first \& if ($form->submitted && $form->validate) { \& # ... more code goes here to do stuff ... \& print $form->confirm; \& } else { \& print $form->render; \& } .Ve .PP This will create a form called \*(L"Order Info\*(R" that will provide a pulldown menu for the \*(L"state\*(R", a textarea for the \*(L"details\*(R", and normal text boxes for the rest. It will then validate the fields specified to the \&\f(CW\*(C`validate\*(C'\fR option appropriately. .Sh "Ex2: order_form.cgi" .IX Subsection "Ex2: order_form.cgi" This is very similar to the above, only it uses the \f(CW\*(C`smartness\*(C'\fR option to fill in the \*(L"state\*(R" options automatically, as well as guess at the validation types we want. I recommend you use the \f(CW\*(C`debug\*(C'\fR option to see what's going on until you're sure it's doing what you want. .PP .Vb 1 \& #!/usr/bin/perl -w .Ve .PP .Vb 2 \& use strict; \& use CGI::FormBuilder; .Ve .PP .Vb 6 \& my $form = CGI::FormBuilder->new( \& header => 1, method => 'POST', \& smartness => 2, debug => 2, \& fields => [qw/first_name last_name email address \& state zipcode credit_card/], \& ); .Ve .PP .Vb 2 \& # This adds on the 'details' field to our form dynamically \& $form->field(name => 'details', cols => '50', rows => '10'); .Ve .PP .Vb 7 \& # try to validate it first \& if ($form->submitted && $form->validate) { \& # ... more code goes here to do stuff ... \& print $form->confirm; \& } else { \& print $form->render; \& } .Ve .PP Since we didn't specify the \f(CW\*(C`title\*(C'\fR option, it will be automatically determined from the name of the executable. In this case it will be \&\*(L"Order Form\*(R". .Sh "Ex3: ticket_search.cgi" .IX Subsection "Ex3: ticket_search.cgi" This is a simple search script that uses a template to layout the search parameters very precisely. Note that we set our options for our different fields and types. .PP .Vb 1 \& #!/usr/bin/perl -w .Ve .PP .Vb 2 \& use strict; \& use CGI::FormBuilder; .Ve .PP .Vb 4 \& my $form = CGI::FormBuilder->new( \& header => 1, template => 'ticket_search.tmpl', \& fields => [qw/type string status category/] \& ); .Ve .PP .Vb 3 \& # Need to setup some specific field options \& $form->field(name => 'type', \& options => [qw/ticket requestor hostname sysadmin/]); .Ve .PP .Vb 2 \& $form->field(name => 'status', type => 'radio', value => 'incomplete', \& options => [qw/incomplete recently_completed all/]); .Ve .PP .Vb 2 \& $form->field(name => 'category', type => 'checkbox', \& options => [qw/server network desktop printer/]); .Ve .PP .Vb 2 \& # Render the form and print it out so our submit button says "Search" \& print $form->render(submit => ' Search '); .Ve .PP Then, in our \f(CW\*(C`ticket_search.tmpl\*(C'\fR \s-1HTML\s0 file, we would have something like this: .PP .Vb 22 \& <html> \& <head> \& <title>Search Engine \& \& \& \&

\&

\& Please enter a term to search the ticket database. Make sure \& to "quote phrases". \&

\& \& Search by for \& \&

\& Status: \&

\& Category: \&

\& \& \& .Ve .PP That's all you need for a sticky search form with the above \s-1HTML\s0 layout. Notice that you can change the \s-1HTML\s0 layout as much as you want without having to touch your \s-1CGI\s0 code. .Sh "Ex4: user_info.cgi" .IX Subsection "Ex4: user_info.cgi" This script grabs the user's information out of a database and lets them update it dynamically. The \s-1DBI\s0 information is provided as an example, your mileage may vary: .PP .Vb 1 \& #!/usr/bin/perl -w .Ve .PP .Vb 4 \& use strict; \& use CGI::FormBuilder; \& use DBI; \& use DBD::Oracle .Ve .PP .Vb 1 \& my $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass'); .Ve .PP .Vb 6 \& # We create a new form. Note we've specified very little, \& # since we're getting all our values from our database. \& my $form = CGI::FormBuilder->new( \& fields => [qw/username password confirm_password \& first_name last_name email/] \& ); .Ve .PP .Vb 5 \& # Now get the value of the username from our app \& my $user = $form->cgi_param('user'); \& my $sth = $dbh->prepare("select * from user_info where user = '$user'"); \& $sth->execute; \& my $default_hashref = $sth->fetchrow_hashref; .Ve .PP .Vb 4 \& # Render our form with the defaults we got in our hashref \& print $form->render(values => $default_hashref, \& title => "User information for '$user'", \& header => 1); .Ve .Sh "Ex5: add_part.cgi" .IX Subsection "Ex5: add_part.cgi" This presents a screen for users to add parts to an inventory database. Notice how it makes use of the \f(CW\*(C`sticky\*(C'\fR option. If there's an error, then the form is presented with sticky values so that the user can correct them and resubmit. If the submission is ok, though, then the form is presented without sticky values so that the user can enter the next part. .PP .Vb 1 \& #!/usr/bin/perl -w .Ve .PP .Vb 2 \& use strict; \& use CGI::FormBuilder; .Ve .PP .Vb 13 \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/sn pn model qty comments/], \& labels => { sn => 'Serial Number', \& pn => 'Part Number' }, \& sticky => 0, \& header => 1, \& required => [qw/sn pn model qty/], \& validate => { sn => '/^\ed{3}-\ed{4}-\ed{4}$/', \& pn => '/^\ed{3}-\ed{4}$/', \& qty => 'INT' }, \& font => 'arial,helvetica' \& ); .Ve .PP .Vb 3 \& # shrink the qty field for prettiness, lengthen model \& $form->field(name => 'qty', size => 4); \& $form->field(name => 'model', size => 60); .Ve .PP .Vb 9 \& if ($form->submitted) { \& if ($form->validate) { \& # Add part to database \& } else { \& # Invalid; show form and allow corrections \& print $form->render(sticky => 1); \& exit; \& } \& } .Ve .PP .Vb 2 \& # Print form for next part addition. \& print $form->render; .Ve .PP With the exception of the database code, that's the whole application. .SH "FREQUENTLY ASKED QUESTIONS (FAQ)" .IX Header "FREQUENTLY ASKED QUESTIONS (FAQ)" There are a couple questions and subtle traps that seem to poke people on a regular basis. Here are some hints. .Sh "I'm confused. Why doesn't \fIfield()\fP work like \s-1CGI\s0's \fIparam()\fP?" .IX Subsection "I'm confused. Why doesn't field() work like CGI's param()?" .RS 4 If you're used to \f(CW\*(C`CGI.pm\*(C'\fR, you have to do a little bit of a brain shift when working with this module. .Sp First, this module is designed to address fields as \fIabstract entities\fR. That is, you don't create a \*(L"checkbox\*(R" or \*(L"radio group\*(R" per se. Instead, you create a field named for the data you want to collect. \fBFormBuilder\fR takes care of figuring out what the most optimal \s-1HTML\s0 representation is for you. .Sp So, if you want a single-option checkbox, simply say something like this: .Sp .Vb 1 \& $form->field(name => 'join_mailing_list', options => ['Yes']); .Ve .Sp If you want it to be checked by default, you add the \f(CW\*(C`value\*(C'\fR arg: .Sp .Vb 2 \& $form->field(name => 'join_mailing_list', options => ['Yes'], \& value => 'Yes'); .Ve .Sp You see, you're creating a field that has one possible option: \*(L"Yes\*(R". Then, you're saying its current value is, in fact, \*(L"Yes\*(R". This will result in \fBFormBuilder\fR creating a single-option field (which is a checkbox by default) and selecting the requested value (meaning that the box will be checked). .Sp If you want multiple values, then all you have to do is specify multiple options: .Sp .Vb 2 \& $form->field(name => 'join_mailing_list', options => [qw/Yes No/], \& value => 'Yes'); .Ve .Sp Now you'll get a radio group, and \*(L"Yes\*(R" will be selected for you! By viewing fields as data entities (instead of \s-1HTML\s0 tags) you get much more flexibility and less code maintenance. If you want to be able to accept multiple values, simply add the \f(CW\*(C`multiple\*(C'\fR arg: .Sp .Vb 2 \& $form->field(name => 'favorite_colors', multiple => 1, \& options => [qw/red green blue]); .Ve .Sp Depending on the number of \f(CW\*(C`options\*(C'\fR you have, you'll get either a set of checkboxes or a multiple select list (unless you manually override this with the \f(CW\*(C`type\*(C'\fR arg). Regardless, though, to get the data back all you have to say is: .Sp .Vb 1 \& my @colors = $form->field('favorite_colors'); .Ve .Sp And the rest is taken care of for you. .Sh "How do I make a multi\-screen/multi\-mode form?" .IX Subsection "How do I make a multi-screen/multi-mode form?" This is easily doable, but you have to remember a couple things. Most importantly, that \fBFormBuilder\fR only knows about those fields you've told it about. So, let's assume that you're going to use a special parameter called \f(CW\*(C`mode\*(C'\fR to control the mode of your application so that you can call it like this: .Sp .Vb 3 \& myapp.cgi?mode=list&... \& myapp.cgi?mode=edit&... \& myapp.cgi?mode=remove&... .Ve .Sp And so on. You need to do two things. First, you need the \f(CW\*(C`keepextras\*(C'\fR option: .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(..., keepextras => 1); .Ve .Sp This will maintain the \f(CW\*(C`mode\*(C'\fR field as a hidden field across requests automatically. Second, you need to realize that since the \f(CW\*(C`mode\*(C'\fR is not a defined field, you have to get it via the \f(CW\*(C`cgi_param()\*(C'\fR method: .Sp .Vb 1 \& my $mode = $form->cgi_param('mode'); .Ve .Sp This will allow you to build a large multiscreen application easily, even integrating it with modules like \f(CW\*(C`CGI::Application\*(C'\fR if you want. .Sp You can also do this by simply defining \f(CW\*(C`mode\*(C'\fR as a field in your \&\f(CW\*(C`fields\*(C'\fR declaration. The reason this is discouraged is because when iterating over your fields you'll get \f(CW\*(C`mode\*(C'\fR, which you likely don't want (since it's not \*(L"real\*(R" data). .Sh "Why won't CGI::FormBuilder work with \s-1POST\s0 requests?" .IX Subsection "Why won't CGI::FormBuilder work with POST requests?" It will, but chances are you're probably doing something like this: .Sp .Vb 2 \& use CGI qw/:standard/; \& use CGI::FormBuilder; .Ve .Sp .Vb 2 \& # Our "mode" parameter determines what we do \& my $mode = param('mode'); .Ve .Sp .Vb 12 \& # Change our form based on our mode \& if ($mode eq 'view') { \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/.../], \& ); \& } elsif ($mode eq 'edit') { \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/.../], \& ); \& } .Ve .Sp The problem is this: Once you read a \f(CW\*(C`POST\*(C'\fR request, it's gone forever. In the above code, what you're doing is having \f(CW\*(C`CGI.pm\*(C'\fR read the \f(CW\*(C`POST\*(C'\fR request (on the first call of \f(CW\*(C`param()\*(C'\fR). .Sp Luckily, there is an easy solution. First, you need to modify your code to use the \s-1OO\s0 form of \f(CW\*(C`CGI.pm\*(C'\fR. Then, simply specify the \f(CW\*(C`CGI\*(C'\fR object you create to the \f(CW\*(C`params\*(C'\fR option of \fBFormBuilder\fR: .Sp .Vb 2 \& use CGI; \& use CGI::FormBuilder; .Ve .Sp .Vb 1 \& my $cgi = CGI->new; .Ve .Sp .Vb 2 \& # Our "mode" parameter determines what we do \& my $mode = $cgi->param('mode'); .Ve .Sp .Vb 15 \& # Change our form based on our mode \& # Note: since it is POST, must specify the 'params' option \& if ($mode eq 'view') { \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/.../], \& params => $cgi # get CGI params \& ); \& } elsif ($mode eq 'edit') { \& my $form = CGI::FormBuilder->new( \& method => 'POST', \& fields => [qw/.../], \& params => $cgi # get CGI params \& ); \& } .Ve .Sp Or, since \fBFormBuilder\fR gives you a \f(CW\*(C`cgi_param()\*(C'\fR function, you could modify your code so you use \fBFormBuilder\fR exclusively. .Sh "How do I make it so that the values aren't shown in the form?" .IX Subsection "How do I make it so that the values aren't shown in the form?" Easy. .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(sticky => 0, ...); .Ve .Sp By turning off the \f(CW\*(C`sticky\*(C'\fR option, you will still be able to access the values, but they won't show up in the form. .Sh "How do I manually override the value of a field?" .IX Subsection "How do I manually override the value of a field?" You must specify the \f(CW\*(C`force\*(C'\fR option: .Sp .Vb 1 \& $form->field(name => 'name_of_field', value => $value, force => 1); .Ve .Sp If you don't specify \f(CW\*(C`force\*(C'\fR, then any \s-1CGI\s0 value will always win. .Sh "How can I change option \s-1XXX\s0 based on a conditional?" .IX Subsection "How can I change option XXX based on a conditional?" Remember that \f(CW\*(C`render()\*(C'\fR can take any option that \f(CW\*(C`new()\*(C'\fR can. This means that you can set some features on your form sooner and others later: .Sp .Vb 1 \& my $form = CGI::FormBuilder->new(method => 'POST'); .Ve .Sp .Vb 1 \& my $mode = $form->cgi_param('mode'); .Ve .Sp .Vb 10 \& if ($mode eq 'add') { \& print $form->render(fields => [qw/name email phone/], \& title => 'Add a new entry'); \& } elsif ($mode eq 'edit') { \& # do something to select existing values \& my %values = select_values(); \& print $form->render(fields => [qw/name email phone/], \& title => 'Edit existing entry', \& values => \e%values); \& } .Ve .Sp In fact, since any of the options can be used in either \f(CW\*(C`new()\*(C'\fR or \&\f(CW\*(C`render()\*(C'\fR, you could have specified \f(CW\*(C`fields\*(C'\fR to \f(CW\*(C`new()\*(C'\fR above since they are the same for both conditions. .ie n .Sh "I can't get ""validate"" to accept my regular expressions!" .el .Sh "I can't get ``validate'' to accept my regular expressions!" .IX Subsection "I can't get validate to accept my regular expressions!" You're probably not specifying them within single quotes. See the section on \f(CW\*(C`validate\*(C'\fR above. .Sh "Can FormBuilder handle file uploads?" .IX Subsection "Can FormBuilder handle file uploads?" It sure can, and it's really easy too. Just change the \f(CW\*(C`enctype\*(C'\fR as an option to \f(CW\*(C`new()\*(C'\fR: .Sp .Vb 6 \& use CGI::FormBuilder; \& my $form = CGI::FormBuilder->new( \& enctype => 'multipart/form-data', \& method => 'POST', \& fields => [qw/filename/] \& ); .Ve .Sp .Vb 1 \& $form->field(name => 'filename', type => 'file'); .Ve .Sp And then get to your file the same way as \f(CW\*(C`CGI.pm\*(C'\fR: .Sp .Vb 2 \& if ($form->submitted) { \& my $file = $form->field('filename'); .Ve .Sp .Vb 6 \& # save contents in file, etc ... \& open F, ">$dir/$file" or die $!; \& while (<$file>) { \& print F; \& } \& close F; .Ve .Sp .Vb 4 \& print $form->confirm(header => 1); \& } else { \& print $form->render(header => 1); \& } .Ve .Sp In fact, that's a whole file upload program right there. .RE .SH "BUGS AND FEATURES" .IX Header "BUGS AND FEATURES" This has been used pretty thoroughly in a production environment for a while now, so it's definitely stable, but I would be shocked if it's bug\-free. Bug reports and \fBespecially patches\fR to fix such bugs are welcomed. .PP I'm always open to entertaining \*(L"new feature\*(R" requests, but before sending me one, first try to work within this module's interface. You can very likely do exactly what you want by using a template. .SH "NOTES" .IX Header "NOTES" Parameters beginning with a leading underscore are reserved for future use by this module. Use at your own peril. .PP This module does a \fBlot\fR of guesswork for you. This means that sometimes (although hopefully rarely), you may be scratching your head wondering \*(L"Why did it do that?\*(R". Just use the \f(CW\*(C`field\*(C'\fR method to set things up the way you want and move on. .PP Due to too many incompatibilities with \s-1CGI\s0.pm, unfortunately \&\f(CW\*(C`CGI::Minimal\*(C'\fR is no longer used. Sorry. .PP The output of the \s-1HTML\s0 generated natively may change slightly from release to release. If you need precise control, use a template. .PP Every attempt has been made to make this module taint-safe (\-T). However, due to the way tainting works, you may run into the message \*(L"Insecure dependency\*(R" or \*(L"Insecure \f(CW$ENV\fR{\s-1PATH\s0}\*(R". If so, make sure you are setting you \f(CW$ENV{PATH}\fR at the top of your script. This is actually a good habit regardless. .SH "SUPPORT" .IX Header "SUPPORT" For support, please start by visiting the FormBuilder website at: .PP .Vb 1 \& www.formbuilder.org .Ve .PP This site has numerous tutorials and other documentation to help you use FormBuilder to its full potential. If you can't find the answer there, then join the mailing list by emailing: .PP .Vb 1 \& fbusers-subscribe@formbuilder.org .Ve .PP To submit patches, please first join the mailing list and post your question or issue. That way we can have a discussion about the best way to address it. .SH "ACKNOWLEDGEMENTS" .IX Header "ACKNOWLEDGEMENTS" This module has really taken off, thanks to very useful input, bug reports, and encouraging feedback from a number of people, including: .PP .Vb 25 \& Jakob Curdes \& Mark Belanger \& Peter Billam \& Brad Bowman \& Jonathan Buhacoff \& Godfrey Carnegie \& Bob Egert \& Adam Foxson \& Florian Helmberger \& Mark Houliston \& Robert James Kaes \& Dimitry Kharitonov \& Randy Kobes \& William Large \& Kevin Lubic \& Robert Mathews \& Mehryar \& Koos Pol \& Shawn Poulson \& Dan Collis Puro \& Stephan Springl \& Ryan Tate \& John Theus \& Remi Turboult \& Andy Wardley .Ve .PP Thanks! .SH "SEE ALSO" .IX Header "SEE ALSO" HTML::Template, Text::Template, Template Toolkit, CGI::Minimal, \&\s-1CGI\s0, CGI::Application .SH "VERSION" .IX Header "VERSION" $Id: FormBuilder.pod,v 2.12 2003/07/25 21:17:30 nwiger Exp nwiger $ .SH "AUTHOR" .IX Header "AUTHOR" Copyright (c) 2001\-2003 Nathan Wiger, Sun Microsystems . All Rights Reserved. .PP This module is free software; you may copy this under the terms of the \s-1GNU\s0 General Public License, or the Artistic License, copies of which should have accompanied your Perl kit.