The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

CGI::QuickForm - Perl module to provide quick CGI forms.

SYNOPSIS

    # Minimal example. (Insecure no error checking.) 

    #!/usr/bin/perl -w
    use strict ;
    use CGI qw( :standard :html3 ) ;
    use CGI::QuickForm ;

    show_form(
        -ACCEPT => \&on_valid_form, # You must supply this subroutine.
        -TITLE  => 'Test Form',
        -FIELDS => [
            { -LABEL => 'Name', },  # Default field type is textfield.
            { -LABEL => 'Age',  },  # Stored in param( 'Age' ).
        ],
    ) ;

    sub on_valid_form {
        my $name = param( 'Name' ) ;
        my $age  = param( 'Age' ) ;
        open PEOPLE, ">>people.tab" ;
        print PEOPLE "$name\t$age\n" ;
        close PEOPLE ;
        print header, start_html( 'Test Form Acceptance' ),
            h3( 'Test Form Data Accepted' ),
            p( "Thank you $name for your data." ), end_html ;
    }


    # All QuickForm options (aide memoir)

    #!/usr/bin/perl -w
    use strict ;
    use CGI qw( :standard :html3 ) ;
    use CGI::QuickForm ;

    show_form(
        -ACCEPT           => \&on_valid_form, 
        -BORDER           => 0,
        -FOOTER           => undef,
        -HEADER           => undef,      
        -INTRO            => undef,
        -LANGUAGE         => 'en',
        -USER_REQUIRED    => undef,
        -USER_INVALID     => undef,
        -TITLE            => 'Test Form',
        -REQUIRED_HTML    => '<span style="font-weight:bold;color:BLUE">+</span>',
        -INVALID_HTML     => '<span style="font-weight:bold;color:RED">*</span>',
        -VALIDATE         => undef,       # Set this to validate the entire record
        -SIZE             => undef,
        -MAXLENGTH        => undef,
        -ROWS             => undef,
        -COLUMNS          => undef,
        -CHECK            => 1,
        -SPACE            => 0, # Output some newlines to assist debugging if 1
        -MULTI_COLUMN     => 0,
        -NAME             => undef,
        -ONSUBMIT         => undef,
        -JSCRIPT          => {},
        -STYLE_FIELDNAME  => '',
        -STYLE_FIELDVALUE => '',
        -STYLE_BUTTONS    => '',
        -STYLE_ROW        => '',
        -STYLE_WHY        => '',
        -TABLE_OPTIONS    => '',
        -FIELDS           => [            
            {
                -LABEL            => 'Personal Details',
                -HEADLINE         => 1,
                -STYLE_FIELDNAME  => '',
                -COLSPAN          => 2,
                -END_ROW          => 1,
            },
            { 
                -LABEL            => 'Name', 
                -START_ROW        => 1,
                -END_ROW          => 1,
                -COLSPAN          => 1,
                -REQUIRED         => undef,
                -TYPE             => 'textfield',
                -VALIDATE         => undef, # Set this to validate the field
                -CLEAN            => undef, # Set this to clean up valid data
                -DESC             => undef,
                -STYLE_FIELDNAME  => '', # If set over-rides form-level setting
                -STYLE_FIELDVALUE => '', # If set over-rides form-level setting
                -STYLE_ROW        => '', # If set over-rides form-level setting
                # Lowercase options are those supplied by CGI.pm
                -name             => undef, # Defaults to -LABEL's value.
                -default          => undef,
                -size             => 30,
                -maxlength        => undef,
            },
            # For all others: same QuickForm options as above
            # and all CGI.pm options (which vary with -TYPE) available 
            { 
                -LABEL     => 'Address', 
                -TYPE      => 'textarea',
                -rows      => 3,
                -columns   => 40,
            },
            { 
                -LABEL     => 'Password', 
                -TYPE      => 'password_field',
            },
            { 
                -LABEL     => 'Hair colour', 
                -TYPE      => 'scrolling_list',
                '-values'  => [ qw( Red Black Brown Grey White ) ],
                -size      => 1,
                -multiples => undef,
            },
            { 
                -LABEL     => 'Worst Sport', 
                -TYPE      => 'radio_group',
                -values    => [ qw( Boxing Cricket Golf ) ], 
                -default   => 'Golf',
            },
            # Any other CGI.pm field can be used in the same way.
        ],
        -BUTTONS           => [
            { -name => 'Add'    },
            { -name => 'Edit'   },
            { -name => 'List'   },
            { -name => 'Remove' },
            { -name => 'Clear', -DEFAULTS => 1 },
        ],
    ) ;
 

DESCRIPTION

show_form, provides a quick and simple mechanism for providing on-line CGI forms.

When show_form executes it presents the form with the fields requested. As you can see from the minimal example at the beginning of the synopsis it will default everything it possibly can to get you up and running as quickly as possible.

If you have specified any validation it will validate when the user presses the submit button. If there is an error it will re-present the form with the erroneous fields marked and with all the data entered in tact. This is repeated as often as needed. Once the user has corrected all errors and the data is valid then your &on_valid_form subroutine will be called so that you can process the valid data in any way you wish.

Note that EXAMPLE #1 and EXAMPLE #2 are in this pod; example1, example2, etc. are supplied as files.

QuickForm form-level (record-level) options

-ACCEPT

Required subroutine reference. This is a reference to the subroutine to execute when the form is successfully completed, i.e. once all the fields and the whole record are valid (either because no validation was requested or because every validation subroutine called returned true). The parameters are accessible via CGI.pm, so your &on_valid_form may look something like this:

    sub on_valid_form {
        my $first_param  = param( 'first' ) ;
        my $second_param = param( 'second' ) ;
        my $third_param  = param( 'third' ) ;

        # Process, e.g. send an email or write a record to a file or database.
        # Give the user a thank you.
    }
-BORDER

Optional integer. This is the border width. Default is zero. You would normally set this to 1 if you are using -DESC to add textual descriptions to your fields.

-BUTTONS

Optional array reference. This is an array of submit buttons. The buttons appear at the bottom of the form, after all the fields. Each button is defined as an anonymous hash, e.g.

    -BUTTONS    => [
        { -name => 'New'    },
        { -name => 'Update' },
        ],

although any other legitimate CGI.pm options may also be given, e.g.

    -BUTTONS    => [
        { -name => 'New',    -value => 'BUTTON_NEW'    },
        { -name => 'Update', -value => 'BUTTON_UPDATE' },
        ],

If you want a button which resets the form to its default values then create an entry like this:

    { -name => 'Clear', -DEFAULTS => 1 },

If no -BUTTONS option array reference is given it will be created with { -name =< 'Submit' } by default. Note that this option replaces the -BUTTONLABEL option. If -BUTTONLABEL is used it will be converted into the new form automatically so old scripts will not be broken. However use of -BUTTONS is recommended for all new work. To see which button has been pressed you might use code like this in your on_valid_form subroutine:

    if( param( 'New' ) ) {
        # New pressed
    }
    elsif( param( 'Update' ) ) {
        # Update pressed
    }
    # etc.
-CHECK

Optional boolean, default is true. When show_form is called it will check (i.e. do validation) providing there are parameters (i.e. the user has filled in the form) and if -CHECK is true. This option would not normally be used. However if you have links which call your form with some parameters (e.g. default values), you will want the form to be displayed with the defaults but without any validation taking place in the first instance. In this situation you would set -CHECK to false. Thus we must cope with the following scenarios:

  1. Form is called with no params - must display blank form and validate when the user presses a button;

  2. Form is called with params (e.g. by clicking a link we've provided) - must display form with any defaults and not validate until the user presses a button;

  3. Form is called with params (as the result of the user pressing a button) - validation must take place.

To achieve the above we need to add an extra field=value pair to the URL we provide and if that is present then skip validation. The field's name must not be one of the form's fields! e.g.

    # If it is to be called from one of our own URLs with something like
    # www.mysite.com/cgi-bin/myscript?colour=green&size=large
    # then we must add in the extra field=value and write the preceeding link
    # for example as:
    # www.mysite.com/cgi-bin/myscript?QFCHK=0&colour=green&size=large 
    # We then use query_string() to set -CHECK to 0 and show the form with the
    # defaults without validating - we'll validate when they press a button. 
    # If its been called as something like www.mysite.com/cgi-bin/myscript
    # then set -CHECK to 1 which gives us standard behaviour:
    # i.e. if there are params then show_form will validate; otherwise it will
    # show the blank form.
    show_form(
        -CHECK => ( query_string() =~ /QFCHK=0/o ? 0 : 1 ), 
        # etc
        ) ;

    # Or more verbosely:
    my $Check = 1 ;
    $Check    = 0 if query_string() =~ /QFCHK=0/o ; 
    show_form(
        -CHECK => $Check,
        # etc
        ) ;

Note that QuickForm discards any query string if it reinvokes itself because of invalid data. This is useful because it means you can use the query string to distinguish between a 'first time' call and subsequent calls as we do here with -CHECK. However if you want a query string parameter to survive these calls we must extract them and pass them ourselves, e.g. via a hidden field.

Optional string. This is used to present any text following the form and if used it must include everything up to and including final "</html>", e.g.:

    my $footer = p( "Thank's for your efforts." ) .
                 h6( "Copyright (c) 1999 Summer plc" ) . end_html ;

    show_form(
        -FOOTER => $footer,
        # etc.

Alternatively, supply a code reference, e.g.:

    sub my_footer {
        print '<hr>The end' . end_html ;
    }

    show_form(
        -FOOTER => \&my_footer,
        # etc.

Note that the code that's called is responsible for printing its own output.

-HEADER

Optional string. This is used to present your own title and text before the form proper. If you use this it must include everything from "Content-type: text/html" onwards. For example:

    my $header = header . start_html( "This is my Title" ) .
                 h2( "My new Form" ) . p( "Please answer the questions!" ) ;

    show_form(
        -HEADER => $header,
        # etc

Alternatively, supply a code reference, e.g.:

    sub my_header {
        print header . start_html( 'A new beginning' ) ;
    }

    show_form(
        -HEADER => \&my_header,
        # etc.

Note that the code that's called is responsible for printing its own output. See example5.

-INTRO

Optional string. If you specify -TITLE you may want to specify this field too; it puts a paragraph of text before the form. The English default is "Please enter the information.", there is a default for each supported language (see -LANGUAGE).

-INVALID_HTML

Optional HTML string. Default is:

    <span style="font-weight:bold;color:RED">*</span>

You can over-ride this to set your own marker to indicate an invalid field. You could use an image tag for example:

    <img src="/images/invalid.jpg" alt="*" />

Note that if you use your own -USER_REQUIRED or -USER_INVALID strings, this string will replace the sequence ~I~ if it occurs.

See example1 and the companion option -REQUIRED_HTML.

-JSCRIPT

Optional hash reference; should contain at least one element 'src' which should contain some Javascript, e.g.

    -JSCRIPT => { src => 'document.Address.myfield.focus()' },

This is just a wrapper for CGI.pm's -script option. (See -NAME and -ONSUBMIT.)

-LANGUAGE

Optional string. This option accepts 'en' (English), 'cy' (Welsh), 'de' (German), 'es' (Spanish), 'fr' (French) and 'he' (Hebrew) - the French translation was done by Babelfish - see CHANGES for the human translators. ('english' is also supported for backward compatibility.) If people provide me with translations I will add other languages. This is used for the presentation of messages to the user, e.g.:

    Please enter the information.
    Fields marked with + are required.
    Fields marked with * contain errors or are empty.

If you want to create your own 'required' or 'invalid' strings using the -USER_REQUIRED and/or -USER_INVALID options and set -LANGUAGE to 'user'. If you want your own 'intro' string set it with -INTRO.

If you're using hebrew, 'he', you will need to define your own header, that specifies an appropriate character set, language and writing direction. For example:

    my $header = header( -charset => 'windows-1255' ) . 
                 start_html( -lang => 'hebrew', -title => 'My Title' ) .  
                 qq{<div dir="RTL">} . 
                 h2( 'My Title' );
    show_form(
        -HEADER => $header,
        -LANGUAGE => 'he',
        # etc.

See example1.

-MULTI_COLUMN

Optional boolean (default false). If false QuickForm behaves as it always has producing a two column table, the first column with field names and the second column with field values. If true QuickForm will put all field names and field values in the same row, except where you force a new row to be used by marking some fields with -END_ROW = 1,>. See the field-level options -START_ROW, -END_ROW and -COLSPAN. See example2 and example4 which have been updated to demonstrate these options.

-NAME

Optional string. If specified this string is given to the start_form() function as its -name option; used for identifying the form for Javascript. (See -JSCRIPT and -ONSUBMIT.)

-ONSUBMIT

Optional string. If specified this string is given to the start_form() function as its -onSubmit option; used with Javascript. (See -JSCRIPT and -NAME.)

-REQUIRED_HTML

Optional HTML string. Default is:

    <span style="font-weight:bold;color:BLUE">+</span>

You can over-ride this to set your own marker to indicate a required field.

Note that if you use your own -USER_REQUIRED or -USER_INVALID strings, this string will replace the sequence ~R~ if it occurs.

See example1 and the companion option -INVALID_HTML.

-TITLE

Required string (unless you use -HEADER). This is used as the form's title and as a header on the form's page - unless you use the -HEADER option (see above) in which case this option is ignored.

-USER_INVALID

Optional string. If specified you must set -LANGUAGE to 'user' and if you are not writing English then you'll need to set -USER_REQUIRED too.

This string is used as the error text for invalid fields. If it contains the character sequence ~I~ that sequence will be replaced with the HTML used to signify an invalid field (which you can override by setting -INVALID_HTML).

-USER_REQUIRED

Optional string. If specified you must set -LANGUAGE to 'user' and if you are not writing English then you'll need to set -USER_INVALID too.

This string is used as the error text for required fields. If it contains the character sequence ~R~ that sequence will be replaced with the HTML used to signify a required field (which you can override by setting -REQUIRED_HTML).

-VALIDATE

Optional subroutine reference. This routine is called after each individual field has been validated. It is given the fields in a name=>value hash. It should either return a simple true (valid) or false (invalid) or a two element list, the first element being a true/false value and the second value either an empty string or an (html) string which gives the reason why the record is invalid. Typically it may have this structure:

    sub valid_record {
        my %field = @_ ;
        my $valid = 1 ;
        # Do some multi-field validation, e.g.
        if( $field{'colour'} eq 'blue' and
            $field{'make'} eq 'estate' ) {
            $valid = 0 ; # No blue estates available.
        }
        # etc.
        $valid ; # Return the valid variable which may now be false.
    }

or now (preferred style):

    sub valid_record {
        my %field = @_ ;
        my $valid = 1 ;
        my $why   = '' ;
        # Do some multi-field validation, e.g.
        if( $field{'colour'} eq 'blue' and
            $field{'make'} eq 'estate' ) {
          $valid = 0 ; # No blue estates available.
          $why   = '<b><i>No blue estates available</i></b>' ;
        }
        # etc.
        ( $valid, $why ) ; 
    }

Both syntaxes work so no existing code need be changed. If the record is invalid the $why element will be shown near the top of the form just before the fields themselves, otherwise (i.e. if the record is valid) it will be ignored.

-COLUMNS

Optional integer. If set then any -TYPE => textarea will have a -columns set to this value unless an explicit -columns is given.

-MAXLENGTH

Optional integer. If set then any -TYPE => textfield will have a -maxlength set to this value unless an explicit -maxlength is given.

-ROWS

Optional integer. If set then any -TYPE => textarea will have a -rows set to this value unless an explicit -rows is given.

-SIZE

Optional integer. If set then any -TYPE => textfield will have a -size set to this value unless an explicit -size is given. For example:

     show_form(
        -ACCEPT => \&on_valid_form, # You must supply this subroutine.
        -TITLE  => 'Test Form',
        -SIZE   => 50,
        -FIELDS => [
            { -LABEL => 'Name', },  
            { -LABEL => 'Age',  }, 
        ],
    ) ;
    # Both the fields will be textfields because that is the default and both
    # will have a -size of 50.


    show_form(
        -ACCEPT    => \&on_valid_form, # You must supply this subroutine.
        -TITLE     => 'Test Form',
        -SIZE      => 50,
        -MAXLENGTH => 70,
        -FIELDS => [
            { 
                -LABEL => 'Name', 
                -CLEAN => \&cleanup, # You must supply this (see later).
            },  
            { -LABEL => 'Age',  }, 
            { 
                -LABEL => 'Country',  
                          # Here we upper case the country.
                -CLEAN => sub { local $_ = shift ; tr/a-z/A-Z/ ; $_ }, 
                -size  => 20,
            }, 
        ],
    ) ;
    # All three fields will be textfields. Name and Age will have a -size of
    # 50 but Country will have a -size of 20. All three will have a -maxlength
    # of 70.
-STYLE_*

These options apply globally and are documented under Styles later.

-SPACE

Optional integer. If true then QuickForm will output some newlines to help make the HTML more human readable for debugging; otherwise no additional whitespace is added. Defaults to false.

-FIELDS

Required array reference. This is an array of hashes; there must be at least one. The fields are displayed in the order given. The options available in each field hash are covered in the next section.

QuickForm field-level options

-CLEAN

Optional subroutine reference. If specified this subroutines will be called for the relevant field if and only if the whole record is valid, i.e. just before calling your on_valid_form subroutine. It will receive a single parameter (the value of the relevant param), and must return a new value. A typical routine might clean up excess whitespace, e.g.:

    sub cleanup {
        local $_ = shift ; # This is the value of param( <fieldname> )

        tr/\t \n\r\f/ /s ; # Convert multiple whitespace to one space.
        s/^\s*//o ;        # Remove leading whitespace.
        s/\s*$//o ;        # Remove trailing whitespace.

        $_ ;
    }
-COLSPAN

Optional integer. Default is 1; ignored if -MULTI_COLUMN is false. If you choose -MULTI_COLUMN and want some fields to span multiple rows then you can use this option to define how many rows are spanned. (Note that every field is two rows wide, one for the fieldname and one for the fieldvalue.)

-DESC

Optional string. This is a short piece of descriptive text which appears above the field and is used to give the user a little guidance on what they should choose or enter. Normally if you use these then you would set the form-level -BORDER option to 1 to help visually group the field and its descriptive text.

-HEADLINE

Optional boolean. Default is false. If set to true then instead of inserting a field, QuickForm will insert a label. This is used to separate blocks of input fields - see example2. If this is true then you will probably want to set -STYLE_FIELDNAME, e.g. to make the text stand out; and also -COLSPAN to the number of columns in the form if using -MULTI_COLUMN. The -LABEL is the text that will be displayed. If using -MULTI_COLUMN any field that preceeds -HEADLINE should normally set -END_ROW to true; this isn't done automatically in case your form has two or more columns and you want to have different headlines above each column. Thus a typical headline field looks like:

    {
        -LABEL           => 'General Information',
        -HEADLINE        => 1,
        -COLSPAN         => 2, # Probably needs to be more for -MULTI_COLUMN
        -END_ROW         => 1,
        -STYLE_FIELDNAME => 'style="background-color:black;color:white;font-weight:bold"', 

    },
-LABEL

Required string. This is the display label for the field. It is also used as the field's name if no -name option is used.

-REQUIRED

Optional boolean. Default is false. If set to true the field must contain something. Should only be used with text fields. It is ignored if -VALIDATE is given since -VALIDATE overrides (see later).

-START_ROW and -END_ROW

Optional booleans, default is true. These options are only relevant if the form-level -MULTI_COLUMN option is set to true in which case these options are used to identify at which fields rows start and end. In practice -START_ROW should never be needed; simply set -END_ROW = 1,> in each field which is to be the last field in a given row. Note that because some fields may need to span several columns e.g. a layout where say the first two fields are side-by-side and the following field is so wide it must take the whole width; the wider field's -COLSPAN setting may need to be set to -COLSPAN = 3,> or similar. See example2 and example4 which have been updated to demonstrate these options.

-STYLE_*

Some of these options may be applied on a per-field basis; they are documented under Styles later.

-TYPE

Optional string. Default is textfield. May be any field supported by CGI.pm.

-VALIDATE

Optional subroutine reference. If specified this subroutine will be called when the user presses the submit button; its argument will be the value of the field. It should either return a simple true (valid) or false (invalid) or a two element list, the first element being a true/false value and the second value either an empty string or an (html) string which gives the reason why the field is invalid. Its typical structure may be:

    sub valid_national_insurance {
        my $ni = shift ;
    
        $ni = uc $ni ;
        ( $ni =~ /^[A-Z]{2}\d{7}[A-Z]$/o ) ? 1 : 0 ;
    }

or now (preferred style):

    sub valid_national_insurance {
        my $ni  = shift ;
        my $why = '<i>Should be 2 letters followed by 7 ' .
                  'digits then a letter</i>' ;
    
        $ni = uc $ni ;
        my $valid = ( $ni =~ /^[A-Z]{2}\d{7}[A-Z]$/o ) ? 1 : 0 ;

        ( $valid, $why ) ; 
    }

Both syntaxes work so no existing code need be changed. If the field is invalid the $why element will be shown immediately to the right of the field it refers to, otherwise (i.e. if the field is valid) it will be ignored.

CGI.pm field-level options

All the other options passed in the hash should be the lowercase options supported by CGI.pm for the particular field type. For example for a -TYPE of textfield the options currently supported are -name, -default, -size and -maxlength; you may use any, all or none of them since CGI.pm always provides sensible defaults. See "All QuickForm options" in the SYNOPSIS above for examples of the most common field types.

Styles

If you wish to use a cascading style sheet with QuickForm then you need to set the -HEADER option to include a <link> tag which includes a reference to your stylesheet.

If you wish to use multiple columns see -MULTI_COLUMN, -START_ROW, -END_ROW and -COLSPAN as well as example2 and example4.

Whether you use a stylesheet for classes or in-line styles you can set the class or style using the -STYLE_* options, e.g.

    -STYLE_FIELDNAME  => qq{style="font-size:12pt;margin:2em;"},
    -STYLE_FIELDVALUE => qq{class="valueclass"},
    -STYLE_ROW        => qq{class="rowclass"},
    -STYLE_DESC       => qq{style="color:darkblue"},

The above styles apply globally to all rows, but can be over-ridden, see later.

    -STYLE_WHY        => qq{style="font-style:italic;color:red"},

Because a popular browser cannot cope with this:

    -STYLE_BUTTONS    => qq{style="font-family:Helvetica;text-align:center;"},

which produces:

    <span style="font-family:Helvetica;text-align:center;>
    # buttons HTML
    </span>

QuickForm also supports (for -STYLE_BUTTONS only) this:

    -STYLE_BUTTONS    => 'center', # or 'centre'

which produces:

    <center>
    # buttons HTML
    </center>

For tables you can set options (because most browsers don't seem to support styles in tables):

    -TABLE_OPTIONS    => qq{BGCOLOR="WHITE"},

See files, example3 (linux-help) and example5 (bicycle) for more examples.

You can of course also apply your own global styles to the existing tags in the normal way.

When -STYLE_DESC, -STYLE_FIELDNAME, -STYLE_FIELDVALUE and -STYLE_ROW are set in show_form at form-level (i.e. not inside the -FIELDS section) they apply globally to every fieldname cell, fieldvalue cell and row respectively. If you require finer control you can set these styles on a per field basis by including them as field-level options, e.g.

    show_form(
        -ACCEPT           => \&on_valid_form,
        -STYLE_FIELDNAME  => 'style="background-color:#AAAAAA"',
        -STYLE_FIELDVALUE => 'style="background-color:#DDDDDD"',
        -FIELDS           => [
                { 
                    -LABEL            => 'Forename', 
                    -STYLE_FIELDNAME  => 'style="background-color:LIGHTGREEN"', 
                    -STYLE_FIELDVALUE => 'style="background-color:YELLOW"', 
                },
        # etc.

If you have set a style at form-level but do not wish it to apply to a particular row you can over-ride either by setting a new style for the row as in the example above or by coding -STYLE_ROW = ' '> for example; we have to use a space because if we used the empty string or undef the global style would be applied.

See example 5.

EXAMPLE #1: Using a form to generate email

This program is provided as an example of QuickForm's capabilities, it is not a production-quality program: it has no error checking and is not secure.

    #!/usr/bin/perl -w
    use strict ;
    use CGI qw( :standard :html3 ) ;
    use CGI::QuickForm ;

    show_form(
        -TITLE  => 'Test Form',
        -ACCEPT => \&on_valid_form, 
        -FIELDS => [
            {
                -LABEL    => 'Forename',
                -REQUIRED => 1,
            },
            {
                -LABEL    => 'Surname',
                -REQUIRED => 1,
            },
            { -LABEL => 'Age', },
            {
                -LABEL    => 'Sex',
                -TYPE     => 'radio_group',
                '-values' => [ qw( Female Male ) ],
            },
        ],
    ) ;

    # This subroutine will only be called if the name fields contain at
    # least one character.
    sub on_valid_form {
        my $forename = param( 'Forename' ) ;
        my $surname  = param( 'Surname' ) ;
        my $age      = param( 'Age' ) ;
        open MAIL, "|/usr/lib/sendmail -t" ; 
        print MAIL "From: test\@localhost\n" .
                   "To: user\@localhost\n" .
                   "Subject: Quick Form Email Test\n\n" .
                   "Name: $forename $surname\n" .
                   "Age:  $age\n" ;
        print header, start_html( 'Test Form Data Accepted' ),
            h3( 'Test Form Data Accepted' ),
            p( "Thank you $forename for your data." ), end_html ;
    }

EXAMPLE #2: Appending data to a file

This program is provided as an example of QuickForm's capabilities, it is not a production-quality program: it has no error checking and is not secure.

    #!/usr/bin/perl -w

    use strict ;
    use CGI qw( :standard :html3 ) ;
    use CGI::QuickForm ;

    show_form(
        -TITLE     => 'Test Form',
        -ACCEPT    => \&on_valid_form, 
        -VALIDATE  => \&valid_form,
        -SIZE      => 40,
        -MAXLENGTH => 60,
        -FIELDS => [
            {
                -LABEL     => 'Forename',
                -VALIDATE  => \&valid_name,
                -CLEAN     => \&cleanup,    # (See earlier for definition.)
            },
            {
                -LABEL     => 'Surname',
                -VALIDATE  => \&valid_name,
                -CLEAN     => \&cleanup,    # (See earlier for definition.)
            },
            {
                -LABEL     => 'Age',
                # &mk_valid_number generates a subroutine (a closure) and
                # returns a reference to that subroutine.
                -VALIDATE  => &mk_valid_number( 3, 130 ), 
                -size      => 10,
                -maxlength => 3,
            },
        ],
    ) ;

    # This will only be called if all the validation routines return true. 
    sub on_valid_form {
        my $forename = param( 'Forename' ) ;
        my $surname  = param( 'Surname' ) ;
        my $age      = param( 'Age' ) ;
        open FILE, ">>namedata.tab" ;
        print FILE "$surname\t$forename\t$age\n" ;
        close FILE ;
        print header, start_html( 'Test Form Data Accepted' ),
            h3( 'Test Form Data Accepted' ),
            p( "Thank you $forename for your data." ), end_html ;
    }

    # This is called to validate the entire form (record).
    # Use a routine like this if there are relationships between fields that
    # must be tested.
    sub valid_form {
        my %rec   = @_ ;
        my $valid = 1 ;
        # We don't allow (perfectly valid!) names like 'John John'.
        my $why   = 'Not allowed to have identical forename and surname' ;
        $valid    = 0 if lc $rec{'Surname'} eq lc $rec{'Forename'} ;
        ( $valid, $why ) ; # $why is ignored if valid.
    }

    sub valid_name {
        my $name  = shift ;
        my $valid = 1 ;
        $valid    = 0 if $name !~ /^\w{2,}$/o ;
        ( $valid, 'Name must have at least 2 letters' ) ; 
    }

    sub mk_valid_number {
        my( $min, $max ) = @_ ;

        sub { 
            my $valid = $_[0] ? ( $min <= $_[0] and $_[0] <= $max ) : 1 ;
            ( $valid, "<i>Should be between $min and $max inclusive</i>" ) ; 
        } ;
    }

mod_perl

QuickForm appears to run fine in CGI scripts that run under Apache::Registry without requiring any changes.

If you want to use QuickForm under pure mod_perl, i.e. outside Apache::Registry they you need to do the following:

  1. Add the following lines at the beginning of your script:

        use Apache::Constants qw( :common ) ;
  2. Ensure that any routines that return to mod_perl return OK. Normally this will be handler() and on_valid_form().

  3. Convert your script into a module by wrapping the show_form() call in a handler subroutine etc.

  4. Copy the module into an Apache subdirectory in your @INC path.

  5. Edit your Apache httpd.conf (or perl.conf) to add a Location for the module.

  6. If you are converting a script that uses url() you may need to add the name of the script, e.g. url() . path_info().

See example6 for a working example that covers all the points above. example6 also has notes at the beginning to explain how to set things up. example6 is a simple conversion of example2 so you can see the simple changes required. Of course you don't have to change your scripts at all if you run them under Apache::Registry.

USING QUICKFORM WITH OBJECT MODULES

If you want to pass QuickForm an on_valid_form function that is in fact an object's method call then instead of:

    -ACCEPT => \&on_valid_form,

you need to write:

    -ACCEPT => sub { $object->on_valid_form },

assuming that you have an object reference called $object and you want it to call its on_valid_form method.

INTRODUCTORY ARTICLE

See http://www.perlpress.com/perl/quickform.html

BUGS

If you get messages like this under pure mod_perl:

    [error] Undefined subroutine &Apache::xxxxxxx::handler called.

the problem is with your configuration not QuickForm, and I won't be able to help you. Please see the copious and high quality documentation at http://perl.apache.org for help with this problem.

If mod_perl prints things like "Content: text/html" at the top of your forms it's a mod_perl issue; check your PerlSendHeader setting (I have it Off).

Some browsers get awfully confused about colouring rows and cells in tables, so if you have problems with this please check the HTML that QuickForm produces (via your browsers View Source command) -- in my test cases QuickForm always outputs correct HTML so the problem if any is with the browser -- however if you find that the HTML is invalid please email me your script plus the HTML shown by View Source (in case I can't run your script).

AUTHOR

Mark Summerfield. I can be contacted as <summer@perlpress.com> - please include the word 'quickform' in the subject line.

Emails giving the URLs of the pages where you use QuickForm would be appreciated!

See CHANGES for acknowledgements.

COPYRIGHT

Copyright (c) Mark Summerfield 1999-2002. All Rights Reserved.

This module may be used/distributed/modified under the LGPL.