Darren Duncan > HTML-FormTemplate-2.03 > HTML::FormTemplate

Download:
HTML-FormTemplate-2.03.tar.gz

Dependencies

Annotate this POD

Related Modules

HTML::EasyTags
Data::Dumper
HTML::Tagset
XML::Simple
CGI::FormMagick
HTML::Mason
CGI::QuickForm
CGI::FormBuilder
HTML::Template
HTML::FillInForm
more...
By perlmonks.org
View/Report Bugs
Module Version: 2.03   Source  

NAME ^

HTML::FormTemplate - Make data-defined persistant forms, reports

DEPENDENCIES ^

Perl Version

        5.004

Standard Modules

        I<none>

Nonstandard Modules

        Class::ParamParser 1.041
        HTML::EasyTags 1.071
        Data::MultiValuedHash 1.081
        CGI::MultiValuedHash 1.09

SYNOPSIS ^

        #!/usr/bin/perl
        use strict;
        use warnings;

        use HTML::FormTemplate;
        use HTML::EasyTags;

        my @definitions = (
                {
                        visible_title => "What's your name?",
                        type => 'textfield',
                        name => 'name',
                        is_required => 1,
                }, {
                        visible_title => "What's the combination?",
                        type => 'checkbox_group',
                        name => 'words',
                        'values' => ['eenie', 'meenie', 'minie', 'moe'],
                        default => ['eenie', 'minie'],
                }, {
                        visible_title => "What's your favorite colour?",
                        type => 'popup_menu',
                        name => 'color',
                        'values' => ['red', 'green', 'blue', 'chartreuse'],
                }, {
                        type => 'submit', 
                },
        );

        my $query_string = '';
        read( STDIN, $query_string, $ENV{'CONTENT_LENGTH'} );
        chomp( $query_string );

        my $form = HTML::FormTemplate->new();
        $form->form_submit_url( 
                'http://'.($ENV{'HTTP_HOST'} || '127.0.0.1').$ENV{'SCRIPT_NAME'} );
        $form->field_definitions( \@definitions );
        $form->user_input( $query_string );

        my ($mail_worked, $mail_failed);
        unless( $form->new_form() ) {
                if( open( MAIL, "|/usr/lib/sendmail -t") ) {
                        print MAIL "To: perl\@DarrenDuncan.net\n";
                        print MAIL "From: perl\@DarrenDuncan.net\n";
                        print MAIL "Subject: A Simple Example HTML::FormTemplate Submission\n";
                        print MAIL "\n";
                        print MAIL $form->make_text_input_echo()."\n";
                        close ( MAIL );
                        $mail_worked = 1;
                } else {
                        $mail_failed = 1;
                }
        }

        my $tagmaker = HTML::EasyTags->new();

        print
                "Status: 200 OK\n",
                "Content-type: text/html\n\n",
                $tagmaker->start_html( 'A Simple Example' ),
                $tagmaker->h1( 'A Simple Example' ),
                $form->make_html_input_form( 1 ),
                $tagmaker->hr,
                $form->new_form() ? '' : $form->make_html_input_echo( 1 ),
                $mail_worked ? "<p>Your favorites were emailed.</p>\n" : '',
                $mail_failed ? "<p>Error emailing your favorites.</p>\n" : '',
                $tagmaker->end_html;

DESCRIPTION ^

This Perl 5 object class can create web fill-out forms as well as parse, error-check, and report their contents. Forms can start out blank or with initial values, or by repeating the user's last input values. Facilities for interactive user-input-correction are also provided.

The class is designed so that a form can be completely defined, using field_definitions(), before any html is generated or any error-checking is done. For that reason, a form can be generated multiple times, each with a single function call, while the form only has to be defined once. Form descriptions can optionally be read from a file by the calling code, making that code a lot more generic and robust than code which had to define the field manually.

OVERVIEW ^

If the calling code provides a MultiValuedHash object or HASH ref containing the parsed user input from the last time the form was submitted, via user_input(), then the newly generated form will incorporate that, making the entered values persistant. Since the calling code has control over the provided "user input", they can either get it live or read it from a file, which is transparent to us. This makes it easy to make programs that allow the user to "come back later" and continue editing where they left off, or to seed a form with initial values. (Field definitions can also contain initial values.)

Based on the provided field definitions, this module can do some limited user input checking, and automatically generate error messages and help text beside the appropriate form fields when html is generated, so to show the user exactly what they have to fix. The "error state" for each field is stored in a hash, which the calling code can obtain and edit using invalid_input(), so that results of its own input checking routines are reflected in the new form.

This class also provides utility methods that you can use to create form field definitions that, when fed back to this class, generates field html that can be used by CGI scripts to allow users with their web browsers to define other form definitions for use with this class.

Note that this class is a subclass of Class::ParamParser, and inherits all of its methods, "params_to_hash()" and "params_to_array()".

RECOGNIZED FORM FIELD TYPES ^

This class recognizes 10 form field types, and a complete field of that type can be made either by providing a "field definition" with the same "type" attribute value, or by calling a method with the same name as the field type. Likewise, groups of related form fields can be made with either a single field definition or method call, for all of those field types.

Standalone fields of the following types are recognized:

0

reset - makes a reset button

0

submit - makes a submit button

0

hidden - makes a hidden field, which the user won't see

0

textfield - makes a text entry field, one row high

0

password_field - same as textfield except contents are bulleted out

0

textarea - makes a big text entry field, several rows high

0

checkbox - makes a standalone check box

0

radio - makes a standalone radio button

0

popup_menu - makes a popup menu, one item can be selected at once

0

scrolling_list - makes a scrolling list, multiple selections possible

Groups of related fields of the following types are recognized:

0

reset_group - makes a group of related reset buttons

0

submit_group - makes a group of related submit buttons

0

hidden_group - makes a group of related hidden fields

0

textfield_group - makes a group of related text entry fields

0

password_field_group - makes a group of related password fields

0

textarea_group - makes a group of related big text entry fields

0

checkbox_group - makes a group of related checkboxes

0

radio_group - makes a group of related radio buttons

0

popup_menu_group - makes a group of related popup menus

0

scrolling_list_group - makes a group of related scrolling lists

Other field types aren't intrinsically recognized, but can still be generated as ordinary html tags by using methods of the HTML::EasyTags class. A list of all the valid field types is returned by the valid_field_type_list() method.

BUGS ^

There is a known issue where the W3C html validator has problems with the generated form code, such as saying hidden fields aren't allowed where they are put, as well as saying that "input" tags should be in a pair. Hopefully a solution for these issues will present itself soon and be in the next release. However, web browsers like Netscape 4.08 still display the HTML properly.

OUTPUT FROM SYNOPSIS PROGRAM ^

This HTML code is from the first time the program runs:

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
        <html>
        <head>
        <title>A Simple Example</title>
        </head>
        <body>
        <h1>A Simple Example</h1>
        <form method="post" action="http://nyxmydomain/dir/script.pl">
        <table>
        <input type="hidden" name=".is_submit" value="1" />
        <tr>
        <td>
        *</td> 
        <td>
        <strong>What's your name?:</strong></td> 
        <td>
        <input type="text" name="name" /></td></tr>

        <tr>
        <td></td> 
        <td>
        <strong>What's the combination?:</strong></td> 
        <td>
        <input type="checkbox" name="words" checked="1" value="eenie" />eenie
        <input type="checkbox" name="words" value="meenie" />meenie
        <input type="checkbox" name="words" checked="1" value="minie" />minie
        <input type="checkbox" name="words" value="moe" />moe</td></tr>

        <tr>
        <td></td> 
        <td>
        <strong>What's your favorite colour?:</strong></td> 
        <td>
        <select name="color" size="1">
        <option value="red" />red
        <option value="green" />green
        <option value="blue" />blue
        <option value="chartreuse" />chartreuse
        </select></td></tr>

        <tr>
        <td></td> 
        <td></td> 
        <td>
        <input type="submit" name="nonamefield001" /></td></tr>

        </table>
        </form>
        <hr />
        </body>
        </html>

This HTML code is the result page of clicking the submit button:

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
        <html>
        <head>
        <title>A Simple Example</title>
        </head>
        <body>
        <h1>A Simple Example</h1>
        <form method="post" action="http://nyxmydomain/dir/script.pl">
        <table>
        <input type="hidden" name=".is_submit" value="1" />
        <tr>
        <td>
        *</td> 
        <td>
        <strong>What's your name?:</strong></td> 
        <td>
        <input type="text" name="name" value="This Is My Name" /></td></tr>

        <tr>
        <td></td> 
        <td>
        <strong>What's the combination?:</strong></td> 
        <td>
        <input type="checkbox" name="words" checked="1" value="eenie" />eenie
        <input type="checkbox" name="words" value="meenie" />meenie
        <input type="checkbox" name="words" checked="1" value="minie" />minie
        <input type="checkbox" name="words" value="moe" />moe</td></tr>

        <tr>
        <td></td> 
        <td>
        <strong>What's your favorite colour?:</strong></td> 
        <td>
        <select name="color" size="1">
        <option selected="1" value="red" />red
        <option value="green" />green
        <option value="blue" />blue
        <option value="chartreuse" />chartreuse
        </select></td></tr>

        <tr>
        <td></td> 
        <td></td> 
        <td>
        <input type="submit" name="nonamefield001" value="Submit Query" /></td></tr>

        </table>
        </form>
        <hr />
        <table>
        <tr><td>
        <strong>What's your name?:</strong></td> <td>This Is My Name</td></tr>
        <tr><td>
        <strong>What's the combination?:</strong></td> <td>eenie<br />minie</td></tr>
        <tr><td>
        <strong>What's your favorite colour?:</strong></td> <td>red</td></tr>
        </table><p>Your favorites were emailed.</p>

        </body>
        </html>

This text is the content of the email message that the program sent:

        Date: Mon, 3 Sep 2001 13:28:19 -0700
        To: perl@DarrenDuncan.net
        From: perl@DarrenDuncan.net
        Subject: A Simple Example HTML::FormTemplate Submission


        Q: What's your name?

        This Is My Name

        ******************************

        Q: What's the combination?

        eenie
        minie

        ******************************

        Q: What's your favorite colour?

        red

SYNTAX ^

This class does not export any functions or methods, so you need to call them using object notation. This means using Class->function() for functions and $object->method() for methods. If you are inheriting this class for your own modules, then that often means something like $self->method().

Methods of this class always "return" their results, rather than printing them out to a file or the screen. Not only is this simpler, but it gives the calling code the maximum amount of control over what happens in the program. They may wish to do post-processing with the generated HTML, or want to output it in a different order than it is generated.

CONSTRUCTOR FUNCTIONS AND METHODS ^

new()

This function creates a new HTML::FormTemplate object and returns it.

initialize()

This method is used by new() to set the initial properties of an object, that it creates.

clone([ CLONE ])

This method initializes a new object to have all of the same properties of the current object and returns it. This new object can be provided in the optional argument CLONE (if CLONE is an object of the same class as the current object); otherwise, a brand new object of the current class is used. Only object properties recognized by HTML::FormTemplate are set in the clone; other properties are not changed.

positional_by_default([ VALUE ])

This method is an accessor for the boolean "positional arguments" property of this object, which it returns. If VALUE is defined, this property is set to it. With methods whose parameters could be either named or positional, when we aren't sure what we are given, do we guess positional? Default is named.

METHODS FOR SETTING USER INPUT AND NEW FORM STATUS ^

reset_to_new_form()

This method sets the boolean property "new form" to true, wipes out any user input (putting form to factory defaults), and clears all error conditions. You can use this method to implement your own "defaults" button if you wish.

user_input([ INPUT ])

This method is an accessor for the "user input" property of this object, which it returns. If INPUT is defined, this property is set to it. This property is a single MultiValuedHash object or HASH ref whose keys are the form fields that the user filled in and whose values are what they entered. These values are used when creating form field html to preserve what the user previously entered, and they are used when doing our own input checking, and they are used when generating input echo reports. This property is also examined when it is set and automatically changes the "new form" property accordingly. The property is undefined by default. The method also clears any error conditions.

new_form([ VALUE ])

This method is an accessor for the boolean "new form" property of this object, which it returns. If VALUE is defined, this property is set to it. If this property is true, then we act like this is the first time we were called. That means that the form is blank except for factory defaults, and there are no error conditions. If this property is false then we are being called again after the user submitted the form at least once, and we do perform input checking. This property is true by default. No other properties are changed.

METHODS FOR DEFAULT FIELD PROPERTIES ^

new_form_determinant([ VALUE ])

This method is an accessor for the boolean "new form determinant" property of this object, which it returns. If VALUE is defined, this property is set to it. This property is the name of a field that we will scan provided user input for to see if this form was submitted. The default property value is ".is_submit". If this field has a true value in the user input, then the form is not new.

default_field_type([ VALUE ])

This method is an accessor for the boolean "default field type" property of this object, which it returns. If VALUE is a valid field type, this property is set to it. If someone tries to make a form field without providing a valid field type, then this is used as the default. The default value is 'textfield'.

default_field_name([ VALUE ])

This method is an accessor for the boolean "default field name" property of this object, which it returns. If VALUE is not an empty string, this property is set to it. If someone tries to make a form field without providing a field name, then this is used as the default name, or as the prefix for a numbered name sequence with stored fields. The default value is 'nonamefield'.

METHODS NAMED AFTER FIELD-TYPES ^

These methods have the same names as field types and each one will make HTML for either a single field or group of related fields of that type. Arguments can be in either named or positional format, or specifically any argument format that Class::ParamParser knows how to handle. If the parser is in doubt, it will guess the format based on the value you set with the positional_by_default() method. The one exception to this is with TYPE; please see its description further below.

The method listings show the positional arguments in the parenthesis beside each method name, and for those any use of brackets means that the enclosed arguments are optional. Below the method name is a vertical list of named arguments; for those, any group of arguments that is enclosed by a bracket-pair are all aliases for each other, and only one should be used at a time. For any of [value, default, label, nolabel] the singular and plural versions are always aliases for each other, and so both are not explicitely shown below.

There are several extra named arguments that apply to each field type which are not shown here; see the EXTRA FIELD-TYPE METHOD ARGUMENTS section for details. While the named argument "linebreak" is shown here for completeness, please see the other section for its explanation also.

reset( NAME[, DEFAULT] )

        NAME
        [DEFAULT or VALUE or LABEL]

This method makes a single reset button that has NAME for its name and optionally DEFAULT as its value. Web browsers may or may not use this value as a button label and they may or may not include the value with form submissions.

submit( NAME[, DEFAULT] )

        NAME
        [DEFAULT or VALUE or LABEL]

This method makes a single submit button that has NAME for its name and optionally DEFAULT as its value. Web browsers may or may not use this value as a button label and they may or may not include the value with form submissions.

hidden( NAME, DEFAULT )

        NAME
        [DEFAULT or VALUE]

This method makes a single hidden field that has NAME for its name and DEFAULT as its value. Nothing is displayed visually by web browsers.

textfield( NAME[, DEFAULT[, SIZE[, MAXLENGTH]]] )

        NAME
        [DEFAULT or VALUE]
        SIZE
        MAXLENGTH

This method makes a single text entry field that has NAME for its name and DEFAULT as its value. The field is one line high and is wide enough to display SIZE characters at once. The user can enter a maximum of MAXLENGTH characters if that argument is set, or is not limited otherwise.

password_field( NAME[, DEFAULT[, SIZE[, MAXLENGTH]]] )

        NAME
        [DEFAULT or VALUE]
        SIZE
        MAXLENGTH

This method makes a single password entry field that has NAME for its name and DEFAULT as its value. The arguments are the same as a textfield but the displayed value is visually bulleted out by the browser.

textarea( NAME[, DEFAULT[, ROWS[, COLS]]] )

        NAME
        [DEFAULT or VALUE or TEXT]
        ROWS
        [COLS or COLUMNS]

This method makes a single big text field that has NAME for its name and DEFAULT as its value. The field is ROWS lines high and is wide enough to display COLS characters at once.

checkbox( NAME[, DEFAULT[, VALUE[, LABEL]]] )

        NAME
        VALUE
        [DEFAULT or CHECKED or SELECTED or ON]
        [LABEL or TEXT]
        NOLABEL

This method makes a single checkbox that has NAME for its name and VALUE as its value. VALUE defaults to 'on' if it is not defined. If DEFAULT is true then the box is checked; otherwise it is not. Unless NOLABEL is true, there is always a user-visible text label that appears beside the checkbox. If LABEL is defined then that is used as the label text; otherwise NAME is used by default.

radio( NAME[, DEFAULT[, VALUE[, LABEL]]] )

        NAME
        VALUE
        [DEFAULT or CHECKED or SELECTED or ON]
        [LABEL or TEXT]
        NOLABEL

This method makes a single radio option that has NAME for its name and VALUE as its value. The arguments are the same as for a checkbox.

popup_menu( NAME, [DEFAULTS], VALUES[, LABELS] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]

This method makes a single popup menu that has NAME for its name and option values populated from the VALUES array ref argument. VALUES defaults to a one-element list containing 'on' if not defined. If DEFAULTS is a hash ref then its keys are matched with elements of VALUES and wherever its values are true then the corresponding menu option is selected; otherwise, DEFAULTS is taken as a list of option VALUES that are to be selected; by default, no options are selected. Similarly, if LABELS is a hash ref then its keys are matched with elements of VALUES and its values provide labels for them; otherwise, LABELS is taken as a list of labels which are matched to VALUES by their corresponding array indices. Since options must always have user-visible labels, any one for which LABELS is undefined will default to using its value as a label. Note that a popup menu is a simplified case of a scrolling list where only one option can be selected and the selected option is the only one visible while the field doesn't have the user's focus (the menu visually opens up when the field has focus).

scrolling_list( NAME, [DEFAULTS], VALUES[, LABELS] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]
        SIZE
        MULTIPLE

This method makes a single scrolling list that has NAME for its name and option values populated from the VALUES array ref argument. The arguments are the same as for a popup menu, except that scrolling lists also support SIZE and MULTIPLE. If MULTIPLE is true then the user can select multiple options; otherwise they can select only one. If SIZE is a number greater than one then that number of options is visually displayed at once; this argument defaults to the count of elements in VALUES if false. Note that setting SIZE to 1 will cause this field to be a popup menu instead.

reset_group( NAME[, DEFAULTS] )

        NAME
        [DEFAULTS or VALUES or LABELS]

This method makes a group of related reset buttons, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

submit_group( NAME[, DEFAULTS] )

        NAME
        [DEFAULTS or VALUES or LABELS]

This method makes a group of related submit buttons, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

hidden_group( NAME, DEFAULTS )

        NAME
        [DEFAULTS or VALUES]

This method makes a group of related hidden fields, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

textfield_group( NAME[, DEFAULTS[, LINEBREAK[, SIZE[, MAXLENGTH]]]] )

        NAME
        [DEFAULTS or VALUES]
        SIZE
        MAXLENGTH

This method makes a group of related text entry fields, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

password_field_group( NAME[, DEFAULTS[, LINEBREAK[, SIZE[, MAXLENGTH]]]] )

        NAME
        [DEFAULTS or VALUES]
        SIZE
        MAXLENGTH

This method makes a group of related password entry fields, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

textarea_group( NAME[, DEFAULTS[, LINEBREAK[, ROWS[, COLS]]]] )

        NAME
        [DEFAULTS or VALUES or TEXT]
        ROWS
        [COLS or COLUMNS]

This method makes a group of related big text fields, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

checkbox_group( NAME, VALUES[, DEFAULTS[, LINEBREAK[, LABELS]]] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]
        NOLABELS

This method makes a group of related checkboxes, which have NAME in common. There is one group member for each element in the array ref VALUES. VALUES defaults to a one-element list containing 'on' if not defined. If DEFAULTS is a hash ref then its keys are matched with elements of VALUES and wherever its values are true then the corresponding box is checked; otherwise, DEFAULTS is taken as a list of box VALUES that are to be checked; by default, no boxes are checked. Similarly, if LABELS is a hash ref then its keys are matched with elements of VALUES and its values provide labels for them; otherwise, LABELS is taken as a list of labels which are matched to VALUES by their corresponding array indices. Unless NOLABELS is true, there is always a user-visible text label that appears beside each checkbox. Any checkbox for which LABELS is undefined will default to using its value for a label.

radio_group( NAME, VALUES[, DEFAULTS[, LINEBREAK[, LABELS]]] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]
        NOLABELS

This method makes a group of related radio options, which have NAME in common. There is one group member for each element in the array ref VALUES. The arguments are the same as for a checkbox_group.

popup_menu_group( NAME, VALUES[, DEFAULTS[, LINEBREAK[, LABELS]]] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]

This method makes a group of related popup menus, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

scrolling_list_group( NAME, VALUES[, DEFAULTS[, LINEBREAK[, LABELS]]] )

        NAME
        VALUES
        [DEFAULTS or CHECKED or SELECTED or ON]
        [LABELS or TEXT]
        SIZE
        MULTIPLE

This method makes a group of related scrolling lists, which have NAME in common. There is one group member for each element in the array ref DEFAULTS.

METHODS FOR MAKING TOPS AND BOTTOMS OF HTML FORMS ^

Besides the field-type methods above, these can be used to make pieces of forms at a time giving you more control of the whole form layout.

start_form([ METHOD[, ACTION] ])

This method returns the top of an HTML form. It consists of the opening 'form' tag. This method can take its optional two arguments in either named or positional format; in the first case, the names look the same as the positional placeholders above, except they must be in lower case. The two arguments, METHOD and ACTION, are scalars which respectively define the method that the form are submitted with and the URL it is submitted to. If either argument is undefined, then the appropriate scalar properties of this object are used instead, and their defaults are "POST" for METHOD and "127.0.0.1" for ACTION. See the form_submit_url() and form_submit_method() methods to access these properties.

end_form()

This method returns the bottom of an HTML form. It consists of the closing 'form' tag.

form_submit_url([ VALUE ])

This method is an accessor for the scalar "submit url" property of this object, which it returns. If VALUE is defined, this property is set to it. This property defines the URL of a processing script that the web browser would use to process the generated form. The default value is "127.0.0.1".

form_submit_method([ VALUE ])

This method is an accessor for the scalar "submit method" property of this object, which it returns. If VALUE is defined, this property is set to it. This property defines the method that the web browser would use to submit form data to a processor script. The default value is "post", and "get" is the other option.

METHODS FOR SETTING AND USING STORED FIELD DEFINITIONS ^

field_definitions([ DEFIN ])

This method is an accessor for the "field definitions" list property of this object, which it returns. If DEFIN is defined, this property is set to it. This property is a list of either MultiValuedHash objects or HASH refs, each of which contains a description for one field or field group that is to be made. Fields will be processed in the same order they appear in this list. The list is empty by default. The method also clears any error conditions.

fields_normalized()

This method returns true if the field definitions have been "normalized". The boolean property that tracks this condition is false by default and only becomes true when normalize_field_definitions() is called. It becomes false when field_definitions() is called.

normalize_field_definitions()

This method edits the "field definitions" such that any fields without names are given one (called "nonamefieldNNN"), any unknown field types become textfields, and any special fields we use internally are created. It returns true when finished. This method is called by any input checking or html making routines if "normalized" is false because it is a precondition for them to work properly.

METHODS FOR MAKING FIELD HTML USING STORED DEFINITIONS ^

field_html([ NAME ])

This method returns generated html code for form fields that were defined using field_definitions(). If NAME is defined it only returnes code for the field (or group) with that name; otherwise it returns a list of html for all fields. This is useful if you want to define your form fields ahead of time, but still want to roll your own complete form.

make_field_html()

This method goes through all the fields and has html made for them, then puts it away for those that need it, namely make_html_input_form() and field_html(). It returns a count of the number of fields generated, which includes all hidden fields and buttons.

METHODS FOR USER INPUT VALIDATION USING STORED DEFINITIONS ^

invalid_input([ NAMES ])

This method is an accessor for the "invalid input" property of this object, which it returns. If NAMES is a valid hash ref, this property is set to it. This property is a hash that indicates which fields have invalid input. The property is undefined by default, and is set when validate_form_input() is called. The optional NAMES argument lets you override the internal input checking to apply your own input checking. If you want both to happen, then call it once with no arguments (internal is automatically done), then edit the results, then call this again providing your new hash as an argument.

validate_form_input()

This method sets the "invalid input" property by applying the various input checking properties of the fields to the user input for those fields. If "new form" is true then all fields are declared to be error free. It returns a count of the number of erroneous fields, and 0 if there are no errors. This method is called by make_html_input_form() and invalid_input() if "invalid input" is false because it is a precondition for them to work properly. If the "validation rule" regular expression does not compile, then Perl automatically throws an exception.

METHODS FOR MAKING WHOLE FORMS AT ONCE ^

make_html_input_form([ TABLE[, LIST] ])

This method returns a complete html input form, including all form field tags, reflected user input values, various text headings and labels, and any visual cues indicating special status for various fields. The first optional boolean argument, TABLE, says to return the form within an HTML table, with one field or field group per row. Field headings and help text appear on the left and the field or group itself appears on the right. All table cells are top-left-aligned, and no widths or heights are specified. If TABLE is false then each field or group is returned in a paragraph that starts with its title. The second optional boolean argument, LIST, causes the resulting form body to be returned as an array ref whose elements are pieces of the page. If this is false then everything is returned in a single scalar.

bad_input_marker([ VALUE ])

This method is an accessor for the string "invalid input marker" property of this object, which it returns. If VALUE is defined, this property is set to it. This string is used to visually indicate in which form fields the user has entered invalid input. It defaults to a question mark ("?").

required_field_marker([ VALUE ])

This method is an accessor for the string "required field marker" property of this object, which it returns. If VALUE is defined, this property is set to it. This string is used to visually indicate which form fields are required, and must be filled in by users for the form to be processed. It defaults to an asterisk ("*").

private_field_marker([ VALUE ])

This method is an accessor for the string "private field marker" property of this object, which it returns. If VALUE is defined, this property is set to it. This string is used to visually indicate which form fields are meant to be private, meaning their content won't be shown to the public. It defaults to a tilde ("~").

METHODS FOR MAKING WHOLE REPORTS AT ONCE ^

make_html_input_echo([ TABLE[, EXCLUDE[, EMPTY[, LIST]]] ])

This method returns a complete html-formatted input "echo" report that includes all the field titles and reflected user input values. Any buttons or hidden fields are excluded. There is nothing that indicates whether the user input has errors or not. There is one heading per field group, and the values from each member of the group are displayed together in a list. The first optional boolean argument, TABLE, says to return the report within an HTML table, with one field or field group per row. All table cells are top-left-aligned, and no widths or heights are specified. If TABLE is false then each field or group input is returned in a paragraph that starts with its title. The second optional boolean argument, EXCLUDE, ensures that any fields that were defined to be "private" are excluded from this report; by default they are included. The third optional string argument, EMPTY, specifies the string to use in place of the user's input where the user left the field empty; by default nothing is shown. The fourth optional boolean argument, LIST, causes the resulting form body to be returned as an array ref whose elements are pieces of the page. If this is false then everything is returned in a single scalar.

make_text_input_echo([ EXCLUDE[, EMPTY[, LIST]] ])

This method returns a complete plain-text-formatted input "echo" report that includes all the field titles and reflected user input values. This report is designed not for web display but for text reports or for inclusion in e-mail messages. Any buttons or hidden fields are excluded. There is nothing that indicates whether the user input has errors or not. There is one heading per field group, and the values from each member of the group are displayed together in a list. For each field, the title is displayed on one line, then followed by a blank line, then followed by the user inputs. The title is preceeded by the text "Q: ", indicating it is the "question". The first optional boolean argument, EXCLUDE, ensures that any fields that were defined to be "private" are excluded from this report; by default they are included. The second optional string argument, EMPTY, specifies the string to use in place of the user's input where the user left the field empty; by default nothing is shown. The third optional boolean argument, LIST, causes the resulting form body to be returned as an array ref whose elements are pieces of the page. If this is false then everything is returned in a single scalar, and there is a delimiter placed between each field or group that consists of a line of asterisks ("*").

empty_field_echo_string([ VALUE ])

This method is an accessor for the string "empty field echo string" property of this object, which it returns. If VALUE is defined, this property is set to it. While making input echo reports, this string is used in place of the user's input where the user left the field empty; this property is "" by default.

METHODS FOR MAKING FORM HTML USING MANUAL FIELD DEFINITIONS ^

field_html_from_defin( DEFIN )

This method creates form field html based on a field template DEFIN, and optionally populates it with user input from a previous form invocation. The field can be any type, including a group. DEFIN must be either a hash ref or an MVH object; if neither is provided then this method aborts and returns undef. This method normally returns a scalar, unless the field template specifies 'list' as an option, in which case an array ref is returned (field groups only).

METHODS FOR MAKING FORM-MAKING FORM DEFINITIONS ^

valid_types([ TYPE ])

This method returns a list of all the form field types that this class can recognize when they are used either in the 'type' attribute of a field definition, or as the name of an html-field-generating method. This list contains the same types listed in the "Recognized Form Field Types" of this documentation. If the optional scalar argument, TYPE, is defined, then this method will instead return true if TYPE is a valid field type or false if not.

valid_multivalue_types([ TYPE ])

This method returns true if a form field of the type defined by the optional scalar argument, TYPE, makes use of a list for its VALUES attribute; otherwise, only a single VALUE can be used. Note that multiple VALUES also means multiple LABELS and DEFAULTS where appropriate. If called without any arguments, this method returns a list of all field types that make use of multiple VALUES. The list that this method works with is a subset of valid_types().

valid_attributes( TYPE[, ATTRIB] )

This method returns a list of all the form field definition attributes that this class can recognize when they are used in defining a field whose type is defined by the scalar argument, TYPE. If the optional scalar argument, ATTRIB, is defined, then this method will instead return true if ATTRIB is a valid field definition attribute or false if not.

HTML-MAKING UTILITY METHODS ^

make_table_from_list( SOURCE[, COLS[, ROWS[, ACROSS]]] )

This method takes a list of HTML or text elements and arranges them into an HTML table structure, returning the whole thing as a scalar. The first argument, SOURCE, is an array ref containing the text we will arrange. The arguments COLS and ROWS respectively indicate the maximum number of columns and rows that SOURCE elements are arranged into; the default for each is 1. Because all source elements must be used, only one of ROWS or COLS is respected; the other is automatically recalcuated from the first; therefore you only need to provide one. COLS takes precedence when both are provided. If the fourth argument ACROSS is true, then source elements are arranged from left-to-right first and then top to bottom; otherwise, the default has elements arranged from top to bottom first and left-to-right second.

PROPERTIES OF FORM FIELD DEFINITIONS ^

The following sections detail all of the properties of form field definitions that are used by this class. That is, if a field definition were a hash, then these properties are the keys and values. The term "argument" may be used here to refer to properties, since they are arguments to the field-type methods.

PROPERTIES FOR BASIC FIELD HTML ^

These properties are the standard ones for making form field html regardless of the method you use to request that HTML; they are used with the field-type methods and with field_definitions() and with field_html_from_defin(). Please see the METHODS NAMED AFTER FIELD-TYPES section above for more detail on usage of these basic properties as well as the circumstances where certain aliases are or are not valid. The singular and plural versions of [value, default, label, nolabel] are always aliases for each other.

type

This string argument specifies which kind of field we are going to make, and it must be in the list given in RECOGNIZED FORM FIELD TYPES. This property defaults to default_field_type() if not valid. This property is used to determine how to handle all of the other properties, so it is important to have. The only time that you don't use this property is with the field-type methods, because the field type is explicitely provided as the method name itself.

name

This string argument is the name of the field we will make. This is needed for matching up user input with the fields it came from on a form submission, so we can do validation, error correction, and reporting. This property defaults to default_field_name() if not provided. Users do not see this name, but the web browsers care about it.

values

This list argument is used with selection-type fields to set the list of options that the user can select from, and can be used with checkbox, radio, popup menu, scrolling list, and groups of each. This property defaults to 'on' if not set for most field types, and to NAME for single checkboxes and radio buttons.

defaults

This list/hash argument provides default user input for the field, which could be from actual live or stored user input, or could be coded default values for the field. Aliases include [values, labels, text, checked, selected, on] depending on the field type.

override

When this boolean argument is true, it ensures that coded DEFAULT values are always used instead of persistant user input for subsequent form invocations. You can use FORCE as an alias for OVERRIDE with all field types.

labels

This list/hash argument provides user-visible text that appears in selection-type fields; these list elements correspond to VALUES elements. If this argument is not provided, the actual VALUES are used as labels.

nolabels

This boolean argument suppresses any field value labels from showing with single or groups of checkboxes or radio buttons.

tag_attr

This optional argument is a hash ref containing miscellaneous html attributes which will be inserted into new form field tags as-is; for field groups these are replicated across all of the group members just as NAME is. Similarly, any named arguments which are not explicitely recognized by this class are treated as html tag attributes as well; note that in the case of a name conflict, the attributes that are pre-existing in TAG_ATTR have lower precedence. Use TAG_ATTR if you want to pass tag attributes which begin with a "-", as such prefixes are removed from normal named method arguments. Under most circumstances, any [size, maxlength, rows, cols/columns, multiple] arguments are moved into here.

min_grp_count

When this numerical argument is defined, methods that make form group fields will make sure that there are at least this many group members; otherwise, there are as many group members made as the greater of 1 and the count of DEFAULTS. This argument can not be used with checkbox_group and radio_group since they always have as many group members as VALUES elements.

list

When this boolean argument is true, methods that make form field groups will return their results in an array ref rather than a string, with the html for each group member in a separate array element. Using this lets you delimit the fields in any way you choose, rather than only the ways this class understands.

linebreak

When this boolean argument is true, methods that make form field groups will join the html for all group members into a string with the members being delimited by linebreaks, that is, '<br />' tags.

table_cols, table_rows, table_acrf

When either TABLE_COLS or TABLE_ROWS is set, methods that make form field groups will arrange the html for all group members into a table using the make_table_from_list() method. The above three arguments correspond to [COLS, ROWS, ACROSS] arguments respectively of that method. For checkbox_group and radio_group only, you can use COLS/COLUMNS and ROWS as aliases for the first two.

PROPERTIES FOR USER-INPUT VALIDATION ^

In cases where user input has been evaluated to be in error, a visual cue is provided to the user in the form of a question mark ("?") that this is so. You need to make your own legend explaining this where appropriate. See bad_input_marker(). Note that any empty strings are filtered from the user input prior to any validation checks are done.

is_required

This boolean property is an assertion that the field must be filled in by the user, or otherwise there is an error condition. A visual cue is provided to the user in the form of an asterisk ("*") that this is so. You need to make your own legend explaining this where appropriate. See required_field_marker().

req_min_count, req_max_count

These numerical properties are assertions of how few or many members of field groups must be filled in or options selected by the user, or otherwise there is an error condition. Each property can be used independently or together.

req_opt_match

This boolean property is an assertion that the user input returned from selection fields or groups must match the list of VALUES provided for that field; if there is any user input that doesn't match, there is an error condition. You can use this to check if users are trying to "cheat" by manually providing selection values, or otherwise check for different error conditions.

validation_rule

This string property is a Perl 5 regular expression that is applied to the user input, one group member at a time. If it evaluates to false on any of them then an error condition is present. If the regular expression fails to compile then Perl will throw an exception automatically during runtime of the input validation routines. You should error-check your regular expressions before passing them to field_definitions().

PROPERTIES FOR NON-FIELD HTML IN FORMS AND REPORTS ^

These properties are only used by make_html_input_form(), make_html_input_echo(), and make_text_input_echo(). Likewise, the "visual cues" mentioned in the previous section only appear in make_html_input_form().

visible_title

This string is the "main title" or "name" or "question" or "prompt" that is visually associated with a form field or field group that lets the user know what the field is for. It is printed in bold type with a colon (":") appended on the end. This title is also used with the input echo reports, as a label or heading for each piece of user input.

help_message

This string is an optional sentance or three that helps the user further, such as explaining the reason for this' fields existence, or by providing examples of valid input. It is printed in smaller type and enclosed in parenthesis.

error_message

This string is an optional sentance or three that only appears when the user didn't enter invalid input. It helps the user further, such as explaining what they did wrong or giving examples of valid input. It is printed in smaller type.

str_above_input

This optional string is HTML code that gets inserted directly before input field HTML while generating a complete form. One possible use of this could be to store a <DIV> tag above the field.

str_below_input

This optional string is HTML code that gets inserted directly after input field HTML while generating a complete form. One possible use of this could be to store a </DIV> tag below the field.

is_private

This boolean property results in a visual cue provided to the user in the form of a tilde ("~"), that you don't intend to make the contents of that field public. You need to make your own legend explaining this where appropriate. See private_field_marker().

exclude_in_echo

This boolean property is an assertion that this field's value will never be shown when reports are generated. This provides an alternative to the more messy redefining of the form field definitions that would otherwise be required to exclude fields that aren't private or hidden or buttons. Normally the calling code is manually displaying the information from fields excluded this way in a location outside the report html.

COMPARISONS WITH CGI.PM ^

The methods of this class and their parameters are designed to be compatible with any same-named methods in the popular CGI.pm class. This class will produce browser-compatible (and often identical) HTML from such methods, and this class can accept all the same argument formats. Exceptions to this include:

0

None of our methods are exported and must be called using object notation, whereas CGI.pm can export any of it's methods.

0

We save in module complexity by not talking to any global variables or files or users directly, expecting rather that the calling code will do this. Methods that generate HTML will return their results so the caller can print them on their own terms, allowing greater control. The calling code must obtain and provide the user's submitted input from previous form incarnations, usually with the user_input() accessor method. If that method is used prior to generating html, then the html methods will behave like those in CGI.pm do when instantiated with a query string, or automatically, or when the "params" were otherwise manipulated. The caller must provide the url that the form submits to, usually with the form_submit_url() accessor method, or the default for this value is "127.0.0.1". That method must be used prior to methods that generate entire forms, in order for them to work as desired. By contrast, CGI.pm uses the current script's url as the default. Of course, if you build forms piece-by-piece and call start_form() yourself, you can give it the "action" argument, which overrides the corresponding property.

0

start_form() doesn't provide a default value for the "encoding" argument, so if the calling code doesn't provide one then it isn't used. By contrast, CGI.pm provides a default encoding of "application/x-www-form-urlencoded".

0

We generally provide a lot more aliases for named arguments to the form field making methods, and these are detailed in the METHODS NAMED AFTER FIELD-TYPES part of this documentation. This is partly to maintain backwards compatability with the aliases that CGI.pm uses, and partly to provide a more consistant argument names between the various methods, something that CGI.pm doesn't always do. For example, "value" is an alias for "default" in every method where they don't mean different things. Another example is that the singular and plural versions of the [default, value, label, nolabel] arguments are always aliases for each other. Another reasoning for this aliasing is to provide a consistant interface for those who are used to giving all the literal HTML names for various arguments, which is exactly what HTML::EasyTags uses. In the cases where our field argument isn't a true HTML argument, and rather is the text that goes outside the tag (such as textarea values or checkbox labels), we accept "text" as aliases, which is the exact convention that HTML::EasyTags uses when you want to specify such text when using named parameters; this makes literalists happy.

0

The arguments "default" and "labels" in our field making methods can be either an ARRAY ref or a HASH ref (or a scalar) and we can handle them appropriately; this choice translates to greater ease of use. By contrast, CGI.pm only takes Hashes for labels.

0

Our checkbox_group and radio_group methods do not recognize some of the special parameters that CGI.pm uses to organize new fields into tables, namely [colheaders, rowheaders]. However, we do support [cols/columns, rows] for those field types only; these parameters are aliases for the [table_cols, table_rows] parameters that work with all field group types. While we don't support [colheaders, rowheaders], we do provide a new "list" argument so field groups aren't joined at all and the caller can organize them however they like.

0

We don't give special treatment to any of the special JavaScript related parameters to field making methods that CGI.pm does, and so we use them as ordinary and miscellaneous html attributes.

0

We save on complexity and don't have a special field type called "defaults" like CGI.pm does. Rather, calling code can just ask for a "submit" button with an appropriate name, and then call our reset_to_new_form() method if they discover it was clicked on during a previous form invocation. This method has the same effect, wiping out anything the user entered, but the caller has more control over when the wipeout occurs. For that matter, simply not setting the user_input() property would have the same effect.

0

We don't currently make "File Upload" fields or a "Clickable Image" buttons or "Javascript Action" buttons that CGI.pm does, although we make all the other field types. You can still use HTML::EasyTags to make HTML for these, however. We do make standalone radio buttons, which CGI.pm does not (as a special case like checkbox anyway), and we do make groups of all field types that we can make singles of, whereas CGI.pm only supports groups of checkboxes and radio buttons.

0

We can both predefine all fields before generating them, which CGI.pm does not, and we can also define fields as-needed in the same manner that CGI.pm does.

AUTHOR ^

Copyright (c) 1999-2003, Darren R. Duncan. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. However, I do request that this copyright information and credits remain attached to the file. If you modify this module and redistribute a changed version then please attach a note listing the modifications. This module is available "as-is" and the author can not be held accountable for any problems resulting from its use.

I am always interested in knowing how my work helps others, so if you put this module to use in any of your own products or services then I would appreciate (but not require) it if you send me the website url for said product or service, so I know who you are. Also, if you make non-proprietary changes to the module because it doesn't work the way you need, and you are willing to make these freely available, then please send me a copy so that I can roll desirable changes into the main release.

Address comments, suggestions, and bug reports to perl@DarrenDuncan.net.

CREDITS ^

Thanks to Lincoln D. Stein for setting a good interface standard in the HTML-related methods of his CGI.pm module. I was heavily influenced by his interfaces when designing my own. Thanks also because I borrowed ideas for my Synopsis program from his aforementioned module.

Thanks to Geir Johannessen <geir.johannessen@nextra.com> for alerting me to several obscure bugs in my POD; these only showed up when manifying, whereas MacPerl's Shuck and CPAN's HTMLizer rendered it properly.

SEE ALSO ^

perl(1), Class::ParamParser, HTML::EasyTags, Data::MultiValuedHash, CGI::MultiValuedHash, CGI::Portable, CGI, CGI::FormMagick, CGI::QuickForm, CGI::Validate.

syntax highlighting: