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

NAME

        HTML::FormWizard - Forms HTML made simple.

SYNOPSIS

        # this script does almost the same that CGI.pm
        # example. And, yes, I use CGI, that is,
        # writes a form and write the submited values
        
        use CGI();
        use HTML::FormWizard();


        my $form = HTML::FormWizard->new(
          -title        => 'A simple Example',
          -fields => [ 
              { name            => 'name',
                    description => "What's your name?"},
              { name                    => 'words',
                        descritpion     => "What's the combination?",
                        type            => 'check',
                        value           => ['eenie','meenie',
                                'minie',moe'],
                        defaults        => ['eenie','minie'] },
                  { name                => 'color',
                    description => "What's your favorite color?",
                    type                => 'list',
                    value               => ['red','green',
                                'blue','chartreuse']}
                ]
        );
        
        # Well, That almost it... But now, that do other things...
        
        # Append field another list field, this one with
        # descriptions, for example... that you must select, 
        # initially saying "--Select Please--".
        
        $form->add(
                { name          => 'country',
                  description   => 'Where did you born?',
                  type                  => 'list',
                  value => 
                                { pt => 'Portugal',
                                  us => 'United States',
                                  uk => 'United Kingdom',
                                  fr => 'France',
                                 '--' => 'Other',
                                 ''     => '--Select Please--'},
                 default                => '',
                 needed                 => 1 }
        );

        # And just one more... A password field, that must 
        # have 3 to 8 characters length, and you want to
        # validate with a function you wrote...
        
        $form->add( 
                { name          => 'password',
                  type          => 'password',
                  minlen        => 3,
                  maxlen        => 8,
                  validate      => sub {
                        my $pass = shift;
                        return 0 if (($pass =~ /\d/) 
                                        and ($pass =~ /[a-zA-Z]/)
                                        and ($pass =~ /\W/));
                        return "The field password must have at least a number,".
                                        " a letter and a symbol";
                  },
                  needed    => 1
                }
        );
                        
        # And now... let's get the results!!!
        
        if (my $data=$form->run) {
                print 
                qq(
                        Your name id $$data{name}<br>
                        The Keywords are: ), 
                                join(", ", @{$$data{words}}),qq(<br>
                        Your Favorite Color is $$data{color}<br>
                        Your birth country is $$data{country}<br>
                        And you password is $$data{password}<br>
                )
        }

DESCRIPTION

There are to much libs that write forms, and only a few that process both things, that is, write HTML forms, and retrieve the data send by the user.

Or... in a more correct way... That handles everything between the first request and the correct data introduction. Why should every program we devel ask some module to create a form, and then ask some other to verify that the submit is correct? Or why should it verify the data?

HTML::FormWizard was wrote for that.

It uses CGI to retrieve data from the requests, and the HTML forms are produced using an object template that if not provided, will be $self (a self reference).

METHODS

The following methods are available (for properties list, see above):

$form = HTML::FormWizard->new([$property => $value]+);

Constructor for the FormWizard. Returns a reference for a HTML::FormWizard object.

$form->set([$property => $value]+);

This method allow you to set the properties that you didn't set initially with new(). This methos only allow you to set a property for each call.

With new() you can set as much properties as you want, but set was thought to modify values predefined or values that you can't know when you init the object.

$form->add([$field]+);

This method allows you to add fields to the fields list at any time.

For field properties see below.

HTML::FormWizard::validate($fieldsref,$dataref);

This function allows validation of a datahash againt a fields list. This allows you to create an hash of data received by email or already on a database and verify that it is valid for a fields list.

This function is used internally to verify that data. It's called by run() method.

my $dataref = $form->getdata([$field]+);

Loads the data from the request and returns a reference to a datahash.

This method receives a list of fields, so it can be called recursively to handle group items.

It returns a HASH with pair:

        { fieldname => fieldvalue }

fieldvalue is an ARRAYREF

This happens when fieldvalue is more than a value. The values for mlist and checkboxes are frequently of this time.

fieldvalue is an HASHREF

This happens to every named group. One of the group type is group.

In true, group is not an field, but a group of field. If a group have name getdata will create an fieldpair with the key equal to the group name property and the value equal to an HASHREF to an hash of VALUES, with the same structure.

my $data = $form->run();

Verify when the request is a submission to the form or just a form request, and in the first case it calls getdata and validade to verify the data. If the data is valid return a reference to the datahash (see getdata() for datahash format).

$form->write;

Writes the HTML to the form. This function is called by $form->run. In true it calls the functions from the template property to write the help.

See more about the template above.

Templates

The template must return a complete HTML page with only the folling calls:

        print 
        $template->header(),
        $template->form_header($title,$method,$url,$encoding,$erro),
        $template->form_footer(),
        $template->footer();

This must write a complete HTML page.

However, here are still missing some other methods.

The important to remember now is ... Templates don't print, return. Why?

That way it's up to the module when he really must print the HTML, and it can be used to print to files, without the file handler been carry for every single function.

$template->header;

This method must create the HTML header for every page. This Header is mustn't open nothing that the footer method will not close.

For example, if the header creates a table to preserve space for something but the form, the table must be closed on the header itself or in the footer method.

It can be closed anywhere else.

$template->form_header($title,$url[,$meth[,$enctype[,$erro]]]);

This method receive up to five parameters:

$title

This is the value that should be the heading line for the form.

$url

The URI where the submission should be done.

$meth

The HTTP Method to use.

$enctype

The Encoding that should be used to make the submission.

$erro

The field description for a invalid field value. Must be used to show a error message.

$template->form_field($fieldname,$fieldhtml);

This method from the template must write a form field. It receive to parameters:

$fieldname

This is a description to the field. It's the label that the user must see associated to the field.

$fieldhtml

This is the HTML to the field. It is the final HTML, no the field properties to write the HTML.

$template->form_group_init($group);

This method receive only the description for the group. The must start the group. The function $template->form_group_end() will be called to end everything form_group_init() leave open.

$template->form_group_end()

This function get no parameters, and must close any HTML tag that the previous open form_group_init() leave open, or return the HTML to show that the group ends here.

$template->form_actions()

This method receive a list of HTML strings, one for each action button or image that the form must have.

$template->form_footer();

This must close any HTML tag that the call to $template->form_footer() leave.

It receive no parameters.

$template->footer

This function must complete the HTML document.

HTML::FormWizard Properties

The list of properties listed new can be set on new(), or later with set(). See this methods documentation for more informations about them.

-title

This is the title for the form, the heading that is write by

        $template->form_init(); 

The value for this property must be a string. For exemple:

        $form->set(-title => 'Simple Test Form');

-url

This property defines the URL to where the post will be done.

For example:

        $form->set(-url => 'http://www.camelot.co.pt/forms/zbr.html');

-method

This property defines the HTTP method that will be used to submit the data. The default to this value is POST.

-encoding

Encoding is the type of encoding that will be used for submitting the data from the client to the server. Once this library was written to work with itself, and CGI accepts "multipart/form-data" without problems, this is the default value for this property, set it if you will be submitting data to old CGI, or scripts that do not support that format.

-template

The property allows the definition of a diferent template for producing the HTML to the form. The default value for this value is the $self reference.

The template is any object that have the functions listed in the previous section.

-cgi

This property must be a reference to CGI or any other lib that can param() and print in a compatible way with CGI.

If this property is not defined, the values will never be returned and the form will always printed to STDOUT.

-fields

This is a reference for a list of form fields. See next section for details.

-actions

This is a reference to a list of buttons and image inputs. See after Fields Details for details about actions.

Fields Details

Diferent field types have diferents properties. The diferent valid types are:

Each Field is an HASH, with the property name as key. The property that defines the type of field is type.

For example:

        { type => 'line',
          name => 'zbr' }

Defines a simple inputbox field named 'zbr'.

type

This defines the type of field. Valid values for type are:

        line
        passwd or password
        check or checkbox
        radio
        list
        mlist
        text
        file
        hidden

        or

        group

Any other value will be ignored and line type will be created if possible.

name

Every field must have a property name, or will not be created. This field is needed to retrieve the data also, so it can't be omitted.

There is only one exception to this: the groups don't need a name.

BUT, if a group don't have name, the field values will be stay on the base data HASH, and not in a sub HASH.

description

This property is optional. If not defined, the module will create it with ucfirst(name).

Used for the field label.

validate

This property is optional. If used, it must be a function that receives a string or an arrayref, depending on the type of field, and return false or an error string to be printed in the form requesting the repost.

datatype

This property is still experimental, and actually only validates 6 diferent kind of values:

        email => validate email address;
        phone => validate phone numbers;
        pt_cp => portuguese postal codes;
        us_cp => american postal codes;
        ipv4  => IP addresses;
        ccard => Credit cards.

Others will be implementated as soon as possible.

Type specific field properties

Some of the properties listed on this section applies to more than one field type, but may differ on the final result.

line and passwd

This is normal inputbox (filled with * for passwd).

Its properties are:

         value

Must be a scalar, and will be the default value for the field.

         size

Must be a number. Will be assigned to the SIZE property of the INPUT in HTML.

         maxlen

Maxlen is the max number of character the field will receive. It is assign to the input box, but will also be verified be validate().

         minlen

minlen isn't defined by HTML, so it will only be verified by validate function.

radio

This can be a single radio button or a group of radio buttons.

         value

Depending on what you want, the value property for radio fields must be diferent things too.

If you want s single radio button (I know, it's usual, but...), The value Property can be a scalar.

If you want a group of radio buttons, the value property can be either an ARRAY or an HASH. In the first case the each element of the ARRAY will be used for the value of the radio and for the label associated with it. In the second case (when value is a HASH), the keys will be used as values and the values in the HASH will be uses as labels.

         default

This must be a scalar containning the value initially selected.

         cols

This sets the number of radio buttons for line.

checkbox

This is a checkbox or a group of checkboxes. See radio for details about properties.

         defaults

This property is used when you have more than one checkbox. This is a list of all the default checked boxes.

COPYRIGHT

Copyright 2002 Merlin, The Mage - camelot.co.pt

This library if open source, you can redistribute it and/or modify it under the same terms as Perl itself.

AUTHOR

Merlin, The Mage <merlin@camelot.co.pt>