|
NAMECGI::FormBuilder - Easily generate and process stateful formsSYNOPSISuse CGI::FormBuilder; # Assume we did a DBI query to get existing values my $dbval = $sth->fetchrow_hashref; # First create our form my $form = CGI::FormBuilder->new( name => 'acctinfo', method => 'post', stylesheet => '/path/to/style.css', values => $dbval, # defaults ); # Now create form fields, in order # FormBuilder will automatically determine the type for you $form->field(name => 'fname', label => 'First Name'); $form->field(name => 'lname', label => 'Last Name'); # Setup gender field to have options $form->field(name => 'gender', options => [qw(Male Female)] ); # Include validation for the email field $form->field(name => 'email', size => 60, validate => 'EMAIL', required => 1); # And the (optional) phone field $form->field(name => 'phone', size => 10, validate => '/^1?-?\d{3}-?\d{3}-?\d{4}$/', comment => '<i>optional</i>'); # Check to see if we're submitted and valid if ($form->submitted && $form->validate) { # Get form fields as hashref my $field = $form->fields; # Do something to update your data (you would write this) do_data_update($field->{lname}, $field->{fname}, $field->{email}, $field->{phone}, $field->{gender}); # Show confirmation screen print $form->confirm(header => 1); } else { # Print out the form print $form->render(header => 1); } DESCRIPTIONIf this is your first time using FormBuilder, you should check out the website for tutorials and examples at <http://formbuilder.org>.You should also consider joining the google group at <http://groups.google.com/group/perl-formbuilder>. There are some pretty smart people on the list that can help you out. OverviewI 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 haven't really been any tools out there that streamline the process. Many modules simply substitute Perl for HTML code:# The manual way print qq(<input name="email" type="text" size="20">); # The module way print input(-name => 'email', -type => 'text', -size => '20'); The problem is, that doesn't really gain you anything - you still have just as much code. Modules like "CGI.pm" are great for decoding parameters, but not for generating and processing whole forms. The goal of CGI::FormBuilder (FormBuilder) is to provide an easy way for you to generate and process entire CGI form-based applications. Its main features are:
Plus, the native HTML generated is valid XHTML 1.0 Transitional. Quick ReferenceFor the incredibly impatient, here's the quickest reference you can get:# Create form my $form = CGI::FormBuilder->new( # Important options fields => \@array | \%hash, # define form fields header => 0 | 1, # send Content-type? method => 'post' | 'get', # default is get name => $string, # namespace (recommended) reset => 0 | 1 | $str, # "Reset" button submit => 0 | 1 | $str | \@array, # "Submit" button(s) text => $text, # printed above form title => $title, # printed up top required => \@array | 'ALL' | 'NONE', # required fields? values => \%hash | \@array, # from DBI, session, etc validate => \%hash, # automatic field validation # Lesser-used options action => $script, # not needed (loops back) cookies => 0 | 1, # use cookies for sessionid? debug => 0 | 1 | 2 | 3, # gunk into error_log? fieldsubs => 0 | 1, # allow $form->$field() javascript => 0 | 1 | 'auto', # generate JS validate() code? keepextras => 0 | 1 | \@array, # keep non-field params? params => $object, # instead of CGI.pm sticky => 0 | 1, # keep CGI values "sticky"? messages => $file | \%hash | $locale | 'auto', template => $file | \%hash | $object, # custom HTML # HTML formatting and JavaScript options body => \%attr, # {background => 'black'} disabled => 0 | 1, # display as grayed-out? fieldsets => \@arrayref # split form into <fieldsets> font => $font | \%attr, # 'arial,helvetica' jsfunc => $jscode, # JS code into validate() jshead => $jscode, # JS code into <head> linebreaks => 0 | 1, # put breaks in form? selectnum => $threshold, # for auto-type generation smartness => 0 | 1 | 2, # tweak "intelligence" static => 0 | 1 | 2, # show non-editable form? styleclass => $string, # style class to use ("fb") stylesheet => 0 | 1 | $path, # turn on style class= table => 0 | 1 | \%attr, # wrap form in <table>? td => \%attr, # <td> options tr => \%attr, # <tr> options # These are deprecated and you should use field() instead fieldtype => 'type', fieldattr => \%attr, labels => \%hash, options => \%hash, sortopts => 'NAME' | 'NUM' | 1 | \&sub, # External source file (see CGI::FormBuilder::Source::File) source => $file, ); # Tweak fields individually $form->field( # Important options name => $name, # name of field (required) label => $string, # shown in front of <input> type => $type, # normally auto-determined multiple => 0 | 1, # allow multiple values? options => \@options | \%options, # radio/select/checkbox value => $value | \@values, # default value # Lesser-used options fieldset => $string, # put field into <fieldset> force => 0 | 1, # override CGI value? growable => 0 | 1 | $limit, # expand text/file inputs? jsclick => $jscode, # instead of onclick jsmessage => $string, # on JS validation failure message => $string, # other validation failure other => 0 | 1, # create "Other:" input? required => 0 | 1, # must fill field in? validate => '/regex/', # validate user input # HTML formatting options cleanopts => 0 | 1, # HTML-escape options? columns => 0 | $width, # wrap field options at $width comment => $string, # printed after field disabled => 0 | 1, # display as grayed-out? labels => \%hash, # deprecated (use "options") linebreaks => 0 | 1, # insert breaks in options? nameopts => 0 | 1, # auto-name options? sortopts => 'NAME' | 'NUM' | 1 | \&sub, # sort options? # Change size, maxlength, or any other HTML attr $htmlattr => $htmlval, ); # Check for submission if ($form->submitted && $form->validate) { # Get single value my $value = $form->field('name'); # Get list of fields my @field = $form->field; # Get hashref of key/value pairs my $field = $form->field; my $value = $field->{name}; } # Print form print $form->render(any_opt_from_new => $some_value); That's it. Keep reading. WalkthroughLet's walk through a whole example to see how FormBuilder works. We'll start with this, which is actually a complete (albeit simple) form application:use CGI::FormBuilder; my @fields = qw(name email password confirm_password zipcode); my $form = CGI::FormBuilder->new( fields => \@fields, header => 1 ); print $form->render; The above code will render an entire form, and take care of maintaining state across submissions. But it doesn't really do anything useful at this point. So to start, let's add the "validate" option to make sure the data entered is valid: my $form = CGI::FormBuilder->new( fields => \@fields, header => 1, validate => { name => 'NAME', email => 'EMAIL' } ); We now get a whole bunch of JavaScript validation code, and the appropriate hooks are added so that the form is validated by the browser "onsubmit" as well. Now, we also want to validate our form on the server side, since the user may not be running JavaScript. All we do is add the statement: $form->validate; Which will go through the form, checking each field 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. Of course, the above returns a truth value, which we should use to see if the form was valid. That way, we only update our database if everything looks good: if ($form->validate) { # print confirmation screen print $form->confirm; } else { # print the form for them to fill out print $form->render; } However, we really only want to do this after our form has been submitted, since otherwise this will result in our form showing errors even though the user hasn't gotten a chance to fill it out yet. As such, we want to check for whether the form has been "submitted()" yet: if ($form->submitted && $form->validate) { # print confirmation screen print $form->confirm; } else { # print the form for them to fill out print $form->render; } Now that know that our form has been submitted and is valid, we need to get our values. To do so, we use the "field()" method along with the name of the field we want: my $email = $form->field(name => 'email'); Note we can just specify the name of the field if it's the only option: my $email = $form->field('email'); # same thing As a very useful shortcut, we can get all our fields back as a hashref of field/value pairs by calling "field()" with no arguments: my $fields = $form->field; # all fields as hashref To make things easy, we'll use this form so that we can pass it easily into a sub of our choosing: if ($form->submitted && $form->validate) { # form was good, let's update database my $fields = $form->field; # update database (you write this part) do_data_update($fields); # print confirmation screen print $form->confirm; } Finally, let's say we decide that we like our form fields, but we need the HTML to be laid out very precisely. No problem! We simply create an "HTML::Template" compatible template and tell FormBuilder to use it. Then, in our template, we include a couple special tags which FormBuilder will automatically expand: <html> <head> <title><tmpl_var form-title></title> <tmpl_var js-head><!-- this holds the JavaScript code --> </head> <tmpl_var form-start><!-- this holds the initial form tag --> <h3>User Information</h3> Please fill out the following information: <!-- each of these tmpl_var's corresponds to a field --> <p>Your full name: <tmpl_var field-name> <p>Your email address: <tmpl_var field-email> <p>Choose a password: <tmpl_var field-password> <p>Please confirm it: <tmpl_var field-confirm_password> <p>Your home zipcode: <tmpl_var field-zipcode> <p> <tmpl_var form-submit><!-- this holds the form submit button --> </form><!-- can also use "tmpl_var form-end", same thing --> Then, all we need to do add the "template" option, and the rest of the code stays the same: my $form = CGI::FormBuilder->new( fields => \@fields, header => 1, validate => { name => 'NAME', email => 'EMAIL' }, template => 'userinfo.tmpl' ); So, our complete code thus far looks like this: use CGI::FormBuilder; my @fields = qw(name email password confirm_password zipcode); my $form = CGI::FormBuilder->new( fields => \@fields, header => 1, validate => { name => 'NAME', email => 'EMAIL' }, template => 'userinfo.tmpl', ); if ($form->submitted && $form->validate) { # form was good, let's update database my $fields = $form->field; # update database (you write this part) do_data_update($fields); # print confirmation screen print $form->confirm; } else { # print the form for them to fill out print $form->render; } 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. Note: If you are confused at all by the backslashes you see in front of some data pieces above, such as "\@fields", skip down to the brief section entitled "REFERENCES" at the bottom of this document (it's short). METHODSThis 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 you stop and visit:www.formbuilder.org And click on "Tutorials" and "Examples". Then, use the following section as a reference later on. new()This method creates a new $form object, which you then use to generate and process your form. In the very shortest version, you can just specify a list of fields for your form:my $form = CGI::FormBuilder->new( fields => [qw(first_name birthday favorite_car)] ); As of 3.02: my $form = CGI::FormBuilder->new( source => 'myform.conf' # form and field options ); For details on the external file format, see CGI::FormBuilder::Source::File. Any of the options below, in addition to being specified to "new()", can also be manipulated directly with a method of the same name. For example, to change the "header" and "stylesheet" options, either of these works: # Way 1 my $form = CGI::FormBuilder->new( fields => \@fields, header => 1, stylesheet => '/path/to/style.css', ); # Way 2 my $form = CGI::FormBuilder->new( fields => \@fields ); $form->header(1); $form->stylesheet('/path/to/style.css'); The second form is useful if you want to wrap certain options in conditionals: if ($have_template) { $form->header(0); $form->template('template.tmpl'); } else { $form->header(1); $form->stylesheet('/path/to/style.css'); } The following is a description of each option, in alphabetical order:
Note that any other options specified are passed to the "<form>" tag verbatim. For example, you could specify "onsubmit" or "enctype" to add the respective attributes. prepare()This function prepares a form for rendering. It is automatically called by "render()", but calling it yourself may be useful if you are using Catalyst or some other large framework. It returns the same hash that will be used by "render()":my %expanded = $form->prepare; You could use this to, say, tweak some custom values and then pass it to your own rendering object. render()This function renders the form into HTML, and returns a string containing the form. The most common use is simply:print $form->render; You can also supply options to "render()", just like you had called the accessor functions individually. These two uses are equivalent: # this code: $form->header(1); $form->stylesheet('style.css'); print $form->render; # is the same as: print $form->render(header => 1, stylesheet => 'style.css'); Note that both forms make permanent changes to the underlying object. So the next call to "render()" will still have the header and stylesheet options in either case. field()This method is used to both get at field values:my $bday = $form->field('birthday'); As well as make changes to their attributes: $form->field(name => 'fname', label => "First Name"); A very common use is to specify a list of options and/or the field type: $form->field(name => 'state', type => 'select', options => \@states); # you supply @states In addition, when you call "field()" without any arguments, it returns a list of valid field names in an array context: my @fields = $form->field; And a hashref of field/value pairs in scalar context: my $fields = $form->field; my $name = $fields->{name}; Note that if you call it in this manner, you only get one single value per field. This is fine as long as you don't have multiple values per field (the normal case). However, if you have a field that allows multiple options: $form->field(name => 'color', options => \@colors, multiple => 1); # allow multi-select Then you will only get one value for "color" in the hashref. In this case you'll need to access it via "field()" to get them all: my @colors = $form->field('color'); The "name" option is described first, and the remaining options are in order:
cgi_param()The above "field()" method will only return fields which you have explicitly defined in your form. Excess parameters will be silently ignored, to help ensure users can't mess with your form.But, you may have some times when you want extra params so that you can maintain state, but you don't want it to appear in your form. Branding is an easy example: http://hr-outsourcing.com/newuser.cgi?company=mr_propane This could change your page's HTML so that it displayed the appropriate company name and logo, without polluting your form parameters. This call simply redispatches to "CGI.pm"'s "param()" method, so consult those docs for more information. tmpl_param()This allows you to manipulate template parameters directly. Extending the above example:my $form = CGI::FormBuilder->new(template => 'some.tmpl'); my $company = $form->cgi_param('company'); $form->tmpl_param(company => $company); Then, in your template: Hello, <tmpl_var company> employee! <p> Please fill out this form: <tmpl_var form-start> <!-- etc... --> For really precise template control, you can actually create your own template object and then pass it directly to FormBuilder. See CGI::FormBuilder::Template for more details. sessionid()This gets and sets the sessionid, which is stored in the special form field "_sessionid". 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 "CGI::Session".Since you can set the session id via the "_sessionid" field, you can pass it as an argument when first showing the form: http://mydomain.com/forms/update_info.cgi?_sessionid=0123-091231 This would set things up so that if you called: my $id = $form->sessionid; This would get the value "0123-091231" in your script. Conversely, if you generate a new sessionid on your own, and wish to include it automatically, simply set is as follows: $form->sessionid($id); If the sessionid is set, and "header" is set, then FormBuilder will also automatically generate a cookie for you. See "EXAMPLES" for "CGI::Session" example. submitted()This returns the value of the "Submit" button if the form has been submitted, undef otherwise. This allows you to either test it in a boolean context:if ($form->submitted) { ... } Or to retrieve the button that was actually clicked on in the case of multiple submit buttons: if ($form->submitted eq 'Update') { ... } elsif ($form->submitted eq 'Delete') { ... } It's best to call "validate()" 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 "name" option described above. If you're writing a multiple-form app, you should name your forms with the "name" option to ensure that you are getting an accurate return value from this sub. See the "name" option above, under "render()". You can also specify the name of an optional field which you want to "watch" instead of the default "_submitted" 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: mysearch.cgi?lookup=what+to+look+for Normally, "submitted()" would return false since the "_submitted" field is not included. However, you can override this by saying: $form->submitted('lookup'); Then, if the lookup field is present, you'll get a true value. (Actually, you'll still get the value of the "Submit" button if present.) validate()This validates the form based on the validation criteria passed into "new()" via the "validate" option. In addition, you can specify additional criteria to check that will be valid for just that call of "validate()". This is useful is you have to deal with different geos:if ($location eq 'US') { $form->validate(state => 'STATE', zipcode => 'ZIPCODE'); } else { $form->validate(state => '/^\w{2,3}$/'); } You can also provide a Data::FormValidator object as the first argument. In that case, the second argument (if present) will be interpreted as the name of the validation profile to use. A single string argument will also be interpreted as a validation profile name. Note that if you pass args to your "validate()" 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 "validate" option to the "new()" function, and just call the "validate()" function with no arguments. 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 "render()", twiddling a couple options.If you're using templates, you probably want to specify a separate success template, such as: if ($form->submitted && $form->validate) { print $form->confirm(template => 'success.tmpl'); } else { print $form->render(template => 'fillin.tmpl'); } So that you don't get the same screen twice. mailconfirm()This sends a confirmation email to the named addresses. The "to" argument is required; everything else is optional. If no "from" is specified then it will be set to the address "auto-reply" since that is a common quasi-standard in the web app world.This does not send any of the form results. Rather, it simply prints out a message saying the submission was received. 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:name: Nate Wiger email: nate@wiger.org colors: red green blue And so on. You can change this by specifying the "delimiter" and "joiner" options. For example this: $form->mailresults(to => $to, delimiter => '=', joiner => ','); Would produce an email like this: name=Nate Wiger email=nate@wiger.org colors=red,green,blue Note that now the last field ("colors") is separated by commas since you have multiple values and you specified a comma as your "joiner". mailresults() with pluginNow you can also specify a plugin to use with mailresults, in the namespace "CGI::FormBuilder::Mail::*". These plugins may depend on other libraries. For example, this:$form->mailresults( plugin => 'FormatMultiPart', from => 'Mark Hedges <hedges@ucsd.edu>', to => 'Nate Wiger <nwiger@gmail.com>', smtp => $smtp_host_or_ip, format => 'plain', ); will send your mail formatted nicely in text using "Text::FormatTable". (And if you used format => 'html' it would use "HTML::QuickTable".) This particular plugin uses "MIME::Lite" and "Net::SMTP" to communicate directly with the SMTP server, and does not rely on a shell escape. See CGI::FormBuilder::Mail::FormatMultiPart for more information. This establishes a simple mail plugin implementation standard for your own mailresults() plugins. The plugin should reside under the "CGI::FormBuilder::Mail::*" namespace. It should have a constructor new() which accepts a hash-as-array of named arg parameters, including form => $form. It should have a mailresults() object method that does the right thing. It should use "CGI::FormBuilder::Util" and puke() if something goes wrong. Calling $form->mailresults( plugin => 'Foo', ... ) will load "CGI::FormBuilder::Mail::Foo" and will pass the FormBuilder object as a named param 'form' with all other parameters passed intact. If it should croak, confess, die or otherwise break if something goes wrong, FormBuilder.pm will warn any errors and the built-in mailresults() method will still try. mail()This is a more generic version of the above; it sends whatever is given as the "text" argument via email verbatim to the "to" address. In addition, if you're not running "sendmail" you can specify the "mailer" parameter to give the path of your mailer. This option is accepted by the above functions as well.COMPATIBILITYThe following methods are provided to make FormBuilder behave more like other modules, when desired.header()Returns a "CGI.pm" header, but only if "header => 1" is set.param()This is an alias for "field()", provided for compatibility. However, while "field()" does act "compliantly" for easy use in "CGI::Session", "Apache::Request", etc, it is not 100% the same. As such, I recommend you use "field()" in your code, and let receiving objects figure the "param()" thing out when needed:my $sess = CGI::Session->new(...); $sess->save_param($form); # will see param() query_string()This returns a query string similar to "CGI.pm", but ONLY containing form fields and any "keepextras", if specified. Other params are ignored.self_url()This returns a self url, similar to "CGI.pm", but again ONLY with form fields.script_name()An alias for "$form->action".STYLESHEETS (CSS)If the "stylesheet" option is enabled (by setting it to 1 or the path of a CSS file), then FormBuilder will automatically output style classes for every single form element:fb main form table fb_label td containing field label fb_field td containing field input tag fb_submit td containing submit button(s) fb_input input types fb_select select types fb_checkbox checkbox types fb_radio radio types fb_option labels for checkbox/radio options fb_button button types fb_hidden hidden types fb_static static types fb_required span around labels for required fields fb_invalid span around labels for invalid fields fb_comment span around field comment fb_error span around field error message Here's a simple example that you can put in "fb.css" which spruces up a couple basic form features: /* FormBuilder */ .fb { background: #ffc; font-family: verdana,arial,sans-serif; font-size: 10pt; } .fb_label { text-align: right; padding-right: 1em; } .fb_comment { font-size: 8pt; font-style: italic; } .fb_submit { text-align: center; } .fb_required { font-weight: bold; } .fb_invalid { color: #c00; font-weight: bold; } .fb_error { color: #c00; font-style: italic; } Of course, if you're familiar with CSS, you know alot more is possible. Also, you can mess with all the id's (if you name your forms) to manipulate fields more exactly. EXAMPLESI find this module incredibly useful, so here are even more examples, pasted from sample code that I've written:Ex1: order.cgiThis example provides an order form, complete with validation of the important fields, and a "Cancel" button to abort the whole thing.#!/usr/bin/perl use strict; use CGI::FormBuilder; my @states = my_state_list(); # you write this my $form = CGI::FormBuilder->new( method => 'post', fields => [ qw(first_name last_name email send_me_emails address state zipcode credit_card expiration) ], header => 1, title => 'Finalize Your Order', submit => ['Place Order', 'Cancel'], reset => 0, validate => { email => 'EMAIL', zipcode => 'ZIPCODE', credit_card => 'CARD', expiration => 'MMYY', }, required => 'ALL', jsfunc => <<EOJS, // skip js validation if they clicked "Cancel" if (this._submit.value == 'Cancel') return true; EOJS ); # Provide a list of states $form->field(name => 'state', options => \@states, sortopts=> 'NAME'); # Options for mailing list $form->field(name => 'send_me_emails', options => [[1 => 'Yes'], [0 => 'No']], value => 0); # "No" # Check for valid order if ($form->submitted eq 'Cancel') { # redirect them to the homepage print $form->cgi->redirect('/'); exit; } elsif ($form->submitted && $form->validate) { # your code goes here to do stuff... print $form->confirm; } else { # either first printing or needs correction print $form->render; } This will create a form called "Finalize Your Order" that will provide a pulldown menu for the "state", a radio group for "send_me_emails", and normal text boxes for the rest. It will then validate all the fields, using specific patterns for those fields specified to "validate". Ex2: order_form.cgiHere's an example that adds some fields dynamically, and uses the "debug" option spit out gook:#!/usr/bin/perl use strict; use CGI::FormBuilder; my $form = CGI::FormBuilder->new( method => 'post', fields => [ qw(first_name last_name email address state zipcode) ], header => 1, debug => 2, # gook required => 'NONE', ); # This adds on the 'details' field to our form dynamically $form->field(name => 'details', type => 'textarea', cols => '50', rows => '10'); # And this adds user_name with validation $form->field(name => 'user_name', value => $ENV{REMOTE_USER}, validate => 'NAME'); if ($form->submitted && $form->validate) { # ... more code goes here to do stuff ... print $form->confirm; } else { print $form->render; } In this case, none of the fields are required, but the "user_name" field will still be validated if filled in. Ex3: ticket_search.cgiThis 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.#!/usr/bin/perl use strict; use CGI::FormBuilder; my $form = CGI::FormBuilder->new( fields => [qw(type string status category)], header => 1, template => 'ticket_search.tmpl', submit => 'Search', # search button reset => 0, # and no reset ); # Need to setup some specific field options $form->field(name => 'type', options => [qw(ticket requestor hostname sysadmin)]); $form->field(name => 'status', type => 'radio', options => [qw(incomplete recently_completed all)], value => 'incomplete'); $form->field(name => 'category', type => 'checkbox', options => [qw(server network desktop printer)]); # Render the form and print it out so our submit button says "Search" print $form->render; Then, in our "ticket_search.tmpl" HTML file, we would have something like this: <html> <head> <title>Search Engine</title> <tmpl_var js-head> </head> <body bgcolor="white"> <center> <p> Please enter a term to search the ticket database. <p> <tmpl_var form-start> Search by <tmpl_var field-type> for <tmpl_var field-string> <tmpl_var form-submit> <p> Status: <tmpl_var field-status> <p> Category: <tmpl_var field-category> <p> </form> </body> </html> That's all you need for a sticky search form with the above HTML layout. Notice that you can change the HTML layout as much as you want without having to touch your CGI code. Ex4: user_info.cgiThis script grabs the user's information out of a database and lets them update it dynamically. The DBI information is provided as an example, your mileage may vary:#!/usr/bin/perl use strict; use CGI::FormBuilder; use DBI; use DBD::Oracle my $dbh = DBI->connect('dbi:Oracle:db', 'user', 'pass'); # 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)] ); # 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; # Render our form with the defaults we got in our hashref print $form->render(values => $default_hashref, title => "User information for '$user'", header => 1); Ex5: add_part.cgiThis presents a screen for users to add parts to an inventory database. Notice how it makes use of the "sticky" 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.#!/usr/bin/perl use strict; use CGI::FormBuilder; 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 => '/^[PL]\d{2}-\d{4}-\d{4}$/', pn => '/^[AQM]\d{2}-\d{4}$/', qty => 'INT' }, font => 'arial,helvetica' ); # shrink the qty field for prettiness, lengthen model $form->field(name => 'qty', size => 4); $form->field(name => 'model', size => 60); if ($form->submitted) { if ($form->validate) { # Add part to database } else { # Invalid; show form and allow corrections print $form->render(sticky => 1); exit; } } # Print form for next part addition. print $form->render; With the exception of the database code, that's the whole application. Ex6: Session ManagementThis creates a session via "CGI::Session", and ties it in with FormBuilder:#!/usr/bin/perl use CGI::Session; use CGI::FormBuilder; my $form = CGI::FormBuilder->new(fields => \@fields); # Initialize session my $session = CGI::Session->new('driver:File', $form->sessionid, { Directory=>'/tmp' }); if ($form->submitted && $form->validate) { # Automatically save all parameters $session->save_param($form); } # Ensure we have the right sessionid (might be new) $form->sessionid($session->id); print $form->render; Yes, it's pretty much that easy. See CGI::FormBuilder::Multi for how to tie this into a multi-page form. 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.I'm confused. Why doesn't this work like CGI.pm?If you're used to "CGI.pm", you have to do a little bit of a brain shift when working with this module.FormBuilder is designed to address fields as abstract entities. That is, you don't create a "checkbox" or "radio group" per se. Instead, you create a field for the data you want to collect. The HTML representation is just one property of this field. So, if you want a single-option checkbox, simply say something like this: $form->field(name => 'join_mailing_list', options => ['Yes']); If you want it to be checked by default, you add the "value" arg: $form->field(name => 'join_mailing_list', options => ['Yes'], value => 'Yes'); You see, you're creating a field that has one possible option: "Yes". Then, you're saying its current value is, in fact, "Yes". This will result in FormBuilder creating a single-option field (which is a checkbox by default) and selecting the requested value (meaning that the box will be checked). If you want multiple values, then all you have to do is specify multiple options: $form->field(name => 'join_mailing_list', options => ['Yes', 'No'], value => 'Yes'); Now you'll get a radio group, and "Yes" will be selected for you! By viewing fields as data entities (instead of HTML tags) you get much more flexibility and less code maintenance. If you want to be able to accept multiple values, simply use the "multiple" arg: $form->field(name => 'favorite_colors', options => [qw(red green blue)], multiple => 1); In all of these examples, to get the data back you just use the "field()" method: my @colors = $form->field('favorite_colors'); And the rest is taken care of for you. 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 FormBuilder only knows about those fields you've told it about. So, let's assume that you're going to use a special parameter called "mode" to control the mode of your application so that you can call it like this:myapp.cgi?mode=list&... myapp.cgi?mode=edit&... myapp.cgi?mode=remove&... And so on. You need to do two things. First, you need the "keepextras" option: my $form = CGI::FormBuilder->new(..., keepextras => 1); This will maintain the "mode" field as a hidden field across requests automatically. Second, you need to realize that since the "mode" is not a defined field, you have to get it via the "cgi_param()" method: my $mode = $form->cgi_param('mode'); This will allow you to build a large multiscreen application easily, even integrating it with modules like "CGI::Application" if you want. You can also do this by simply defining "mode" as a field in your "fields" declaration. The reason this is discouraged is because when iterating over your fields you'll get "mode", which you likely don't want (since it's not "real" data). Why won't CGI::FormBuilder work with post requests?It will, but chances are you're probably doing something like this:use CGI qw(:standard); use CGI::FormBuilder; # Our "mode" parameter determines what we do my $mode = param('mode'); # 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(...)], ); } The problem is this: Once you read a "post" request, it's gone forever. In the above code, what you're doing is having "CGI.pm" read the "post" request (on the first call of "param()"). Luckily, there is an easy solution. First, you need to modify your code to use the OO form of "CGI.pm". Then, simply specify the "CGI" object you create to the "params" option of FormBuilder: use CGI; use CGI::FormBuilder; my $cgi = CGI->new; # Our "mode" parameter determines what we do my $mode = $cgi->param('mode'); # 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 ); } Or, since FormBuilder gives you a "cgi_param()" function, you could also modify your code so you use FormBuilder exclusively, as in the previous question. How can I change option XXX based on a conditional?To change an option, simply use its accessor at any time:my $form = CGI::FormBuilder->new( method => 'post', fields => [qw(name email phone)] ); my $mode = $form->cgi_param('mode'); if ($mode eq 'add') { $form->title('Add a new entry'); } elsif ($mode eq 'edit') { $form->title('Edit existing entry'); # do something to select existing values my %values = select_values(); $form->values(\%values); } print $form->render; Using the accessors makes permanent changes to your object, so be aware that if you want to reset something to its original value later, you'll have to first save it and then reset it: my $style = $form->stylesheet; $form->stylesheet(0); # turn off $form->stylesheet($style); # original setting You can also specify options to "render()", although using the accessors is the preferred way. How do I manually override the value of a field?You must specify the "force" option:$form->field(name => 'name_of_field', value => $value, force => 1); If you don't specify "force", then the CGI value will always win. This is because of the stateless nature of the CGI protocol. How do I make it so that the values aren't shown in the form?Turn off sticky:my $form = CGI::FormBuilder->new(... sticky => 0); By turning off the "sticky" option, you will still be able to access the values, but they won't show up in the form. I can't get "validate" to accept my regular expressions!You're probably not specifying them within single quotes. See the section on "validate" above.Can FormBuilder handle file uploads?It sure can, and it's really easy too. Just change the "enctype" as an option to "new()":use CGI::FormBuilder; my $form = CGI::FormBuilder->new( enctype => 'multipart/form-data', method => 'post', fields => [qw(filename)] ); $form->field(name => 'filename', type => 'file'); And then get to your file the same way as "CGI.pm": if ($form->submitted) { my $file = $form->field('filename'); # save contents in file, etc ... open F, ">$dir/$file" or die $!; while (<$file>) { print F; } close F; print $form->confirm(header => 1); } else { print $form->render(header => 1); } In fact, that's a whole file upload program right there. REFERENCESThis 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.A reference is taken by preceding the variable with a backslash (\). In our examples above, you saw something similar to this: my @fields = ('name', 'email'); # same as = qw(name email) my $form = CGI::FormBuilder->new(fields => \@fields); Here, "\@fields" is a reference. Specifically, it's an array reference, or "arrayref" for short. Similarly, we can do the same thing with hashes: my %validate = ( name => 'NAME'; email => 'EMAIL', ); my $form = CGI::FormBuilder->new( ... validate => \%validate); Here, "\%validate" is a hash reference, or "hashref". 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 CPAN modules. Finally, there are two more types of references: anonymous arrayrefs and anonymous hashrefs. These are created with "[]" and "{}", respectively. So, for our purposes there is no real difference between this code: my @fields = qw(name email); my %validate = (name => 'NAME', email => 'EMAIL'); my $form = CGI::FormBuilder->new( fields => \@fields, validate => \%validate ); And this code: my $form = CGI::FormBuilder->new( fields => [ qw(name email) ], validate => { name => 'NAME', email => 'EMAIL' } ); Except that the latter doesn't require that we first create @fields and %validate variables. ENVIRONMENT VARIABLESFORMBUILDER_DEBUGThis toggles the debug flag, so that you can control FormBuilder debugging globally. Helpful in mod_perl.NOTESParameters beginning with a leading underscore are reserved for future use by this module. Use at your own peril.The "field()" method has the alias "param()" for compatibility with other modules, allowing you to pass a $form around just like a $cgi object. The output of the HTML generated natively may change slightly from release to release. If you need precise control, use a template. 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 "Insecure dependency" or "Insecure $ENV{PATH}". If so, make sure you are setting $ENV{PATH} at the top of your script. ACKNOWLEDGEMENTSThis module has really taken off, thanks to very useful input, bug reports, and encouraging feedback from a number of people, including:Norton Allen Mark Belanger Peter Billam Brad Bowman Jonathan Buhacoff Godfrey Carnegie Jakob Curdes Laurent Dami Bob Egert Peter Eichman Adam Foxson Jorge Gonzalez Florian Helmberger Mark Hedges Mark Houliston Victor Igumnov Robert James Kaes Dimitry Kharitonov Randy Kobes William Large Kevin Lubic Robert Mathews Mehryar Klaas Naajikens Koos Pol Shawn Poulson Victor Porton Dan Collis Puro Wolfgang Radke David Siegal Stephan Springl Ryan Tate John Theus Remi Turboult Andy Wardley Raphael Wegmann Emanuele Zeppieri Thanks! SEE ALSOCGI::FormBuilder::Template, CGI::FormBuilder::Messages, CGI::FormBuilder::Multi, CGI::FormBuilder::Source::File, CGI::FormBuilder::Field, CGI::FormBuilder::Util, CGI::FormBuilder::Util, HTML::Template, Text::Template CGI::FastTemplateREVISION$Id: FormBuilder.pm 65 2006-09-07 18:11:43Z nwiger $AUTHORCopyright (c) Nate Wiger <http://nateware.com>. All Rights Reserved.This module is free software; you may copy this under the terms of the GNU General Public License, or the Artistic License, copies of which should have accompanied your Perl kit.
Visit the GSP FreeBSD Man Page Interface. |