NAME
HTML::FormHandler - validate and process form data
SYNOPSIS
HTML::FormHandler is based on Form::Processor. The original goal was just to make a Moose version of Form::Processor, but there were issues in maintaining compatibility between the non-Moose and Moose versions. Although very similar to Form::Processor, FormHandler does not intend to be compatible. A substantial number of methods and attributes have been renamed for internal consistency and consistency with Moose usage, and some refactoring has been done.
This first version should be considered non-stable, since I am actively looking for ways to improve it which may result in some api changes.
HTML::FormHandler allows you to define HTML form fields and validators, and will automatically update or create rows in a database, although it can also be used for non-database forms.
One of its goals is to keep the controller interface as simple as possible, and to minimize the duplication of code.
An example of a Catalyst controller that uses an HTML::FormHandler form to update or create a 'Book' record (this example does not use Catalyst::Controller::Role::HTML::FormHandler):
package MyApp::Controller::Book;
use Moose;
use MyApp::Form::Book;
sub edit : Local {
my ( $self, $c, $id ) = @_;
# Create the form object
my $form = MyApplication::Form::Book->new( $id );
$c->stash->{form} = $form;
# Update or create the record if form posted
$form->update_from_form( $c->req->parameters )
if $c->req->method eq 'POST';
# the return will cause the "end" action to use the default
# view to display the form
return unless $c->req->method eq 'POST' && $form->validated;
# form validated, so continue on to some other action
$c->res->redirect( $c->uri_for('view', $form->item->id) );
}
An example of a form class:
package MyApp::Form::User;
use Moose;
extends 'HTML::FormHandler::Model::DBIC';
has '+item_class' => ( default => 'Book' );
sub profile {
return {
fields => [
name => 'Text',
age => 'PosInteger',
birthdate => 'DateTime',
hobbies => 'Multiple',
address => 'Text',
city => 'Text',
state => 'Select',
email => 'Email',
],
dependency => [
['address', 'city', 'state'],
],
];
}
sub validate_age {
my ( $self, $field ) = @_;
$field->add_error('Sorry, you must be 18')
if $field->value < 18;
}
1;
A dynamic form may be created in a controller:
$c->stash->{form} = HTML::FormHandler->new(
item_class => 'Book',
item_id => $id,
schema => $schema,
profile => {
fields => {
first_name => 'Text',
last_name => 'Text'
},
},
);
DESCRIPTION
HTML::FormHandler differs from other form frameworks in that each form is a Perl object. This allows concentrating form definition and validation in one place, and permits easy customization.
HTML::FormHandler does not provide a complex HTML generating facility, but a simple, sample rendering role is provided by HTML::FormHandler::Render::Simple, which will output HTML formatted strings for a field or a form. There are also sample Template Toolkit widget files in the example, documented at HTML::FormHandler::Manual::Templates.
The typical application for FormHandler would be in a Catalyst, DBIx::Class, Template Toolkit web application, but use is not limited to that.
The HTML::FormHandler module is documented here. For more extensive documentation on use and a tutorial, see the manual at HTML::FormHandler::Manual.
ATTRIBUTES
profile
A hashref of field definitions.
The possible keys in the profile hashref are:
required
optional
fields
auto_required
auto_optional
dependency
Example of a profile hashref:
my $profile => {
fields => [
field_one => {
type => 'Text',
required => 1
},
field_two => 'Text,
],
};
For the "auto" profile keys, provide a list of field names. The field types will be determined by calling 'guess_field_type' in the model.
auto_required => ['name', 'age', 'sex', 'birthdate'],
auto_optional => ['hobbies', 'address', 'city', 'state'],
The "dependency" profile key is an arrayref of arrayrefs that contain a list of fields where if one is entered, all fields are required.
dependency => [
['address', 'city', 'state', 'zip'],
['cc_no', 'cc_expires'],
]
name
The form's name. Useful for multiple forms. It's also used to construct the default 'id' for fields. The default is "form" + a one to three digit random number.
In your form:
has '+name' => ( default => 'userform' );
name_prefix
Prefix used for all field names listed in profile when creating each field. This is useful for creating compound form fields where a single field is made up of a collection of fields. The collection of fields can be a complete form. An example might be a field that represents a DateTime object, but is made up of separate day, month, and year fields.
html_prefix
Flag to indicate that the form name is used as a prefix for fields in an HTML form. Useful for multiple forms on the same HTML page. The prefix is stripped off of the fields before creating the internal field name, and added back in when returning a parameter hash from the 'fif' method.
Also see the Field attribute "prename", a convenience function which will return the form name + "." + field name
init_object
If an 'init_object' is supplied on form creation, it will be used instead of the 'item' to pre-populate the values in the form.
This can be useful when populating a form from default values stored in a similar but different object than the one the form is creating.
See 'init_from_object' method
ran_validation
Flag to indicate that validation has already been run.
validated
Flag that indicates if form has been validated
verbose
Flag to print out additional diagnostic information
readonly
"Readonly" is not used by F::P.
field_name_space
Use to set the name space used to locate fields that start with a "+", as: "+MetaText". Fields without a "+" are loaded from the "HTML::FormHandler::Field" name space. If 'field_name_space' is not set, then field types with a "+" must be the complete package name.
num_errors
Total number of errors
updated_or_created
Flag indicating whether the db record in the item already existed (was updated) or was created
user_data
Place to store user data
language_handle, build_language_handle
Holds a Local::Maketext language handle
The builder for this attribute gets the Locale::Maketext language handle from the environment variable $ENV{LANGUAGE_HANDLE}, or creates a default language handler using HTML::FormHandler::I18N
field_counter
Used for numbering fields. Used by set_order method in Field.pm. Useful in templates.
params
Stores HTTP parameters. Also: set_param, get_param, reset_params, delete_param, from Moose 'Collection::Hash' metaclass.
fields
The field definitions as built from the profile. This is a MooseX::AttributeHelpers::Collection::Array, and provides clear_fields, add_field, remove_last_field, num_fields, has_fields, and set_field_at methods.
required
Array of fields that are required
parent_field
This value can be used to link a sub-form to the parent field.
If a form has a parent_field associated with it, errors in the field will be pushed onto the parent_field instead of the current field. This stores a weakened value.
METHODS
new
New creates a new form object. The constructor takes name/value pairs:
MyForm->new(
item => $item,
item_id => $item->id,
);
Or a single item (model row object) or item_id (row primary key) may be supplied:
MyForm->new( $id );
or
MyForm->new( $item );
If the value passed in is a reference then it is assumed to have an "id" method. So:
MyForm->new( $item_object );
is the same as:
MyForm->new(
item => $item_object,
item_id => $item_object->id,
);
The common attributes to be passed in to the constructor are:
item_id
item
name
name_prefix
item_class
profile
init_object
Creating a form object:
my $form = = HTML::FormHandler::Model::DBIC->new(
item_id => $id,
item_class => 'User',
schema => $schema,
profile => {
required => {
name => 'Text',
active => 'Boolean',
},
},
);
The 'item', 'item_id', and 'item_class' attributes are defined in HTML::FormHandler::Model, and 'schema' is defined in HTML::FormHandler::Model::DBIC.
BUILD, BUILDARGS
These are called when the form object is first created (by Moose).
A single argument is an "item" parameter if it's a reference, otherwise it's an "item_id".
First BUILD calls the build_form method, which reads the profile and creates the fields object array.
Then 'init_from_object' is called to load each field's internal value from the 'init_object' or from the 'item', followed by 'load_options' to load values for select fields.
clear
Clears out state information on the form. Normally only used in tests.
build_form
This parses the form profile and creates the individual field objects. It calls the make_field() method for each field.
make_field
$field = $form->make_field( $name, $type );
Maps the field type to a field class, creates a field object and and returns it.
The "$name" parameter is the field's name (e.g. first_name, age).
The second parameter is either a scalar which is the field's type string, or a hashref with a 'type' key containing the field's type.
load_options
For 'Select' or 'Multiple' fields (fields which have an 'options' method), call an "options_$field_name" method if it exists (is defined in your form), or else call the model's "lookup_options" to retrieve the list of options from the database.
An example of an 'options' routine in your form class:
sub options_fruit {
return (
1 => 'Apple',
2 => 'Grape',
3 => 'Cherry',
);
}
See HTML::FormHandler::Field::Select
load_field_options
Load the options array into a field. Pass in a field object, and, optionally, an options array.
dump_fields
Dumps the fields of the form for debugging.
init_from_object
Populates the field 'value' attributes from $form->item by calling a form's custom init_value_$fieldname method, passing in the field and the item. If a custom init_value_ method doesn't exist, uses the generic 'init_value' routine from the model.
The value is stored in both the 'init_value' attribute, and the 'value' attribute.
clear_values
Clears the internal and external values of the form
fif -- "fill in form"
Returns a hash of values suitable for use with HTML::FillInForm or for filling in a form with $form->fif->{fieldname}
.
sorted_fields
Calls fields and returns them in sorted order by their "order" value.
field NAME
Searches for and returns a field named "NAME". Dies on not found.
my $field = $form->field('first_name');
Pass a second true value to not die on errors.
my $field = $form->field('something', 1 );
field_exists
Returns true (the field) if the field exists
validate
Validates the form from the HTTP request parameters. The parameters must be a hash ref with multiple values as array refs.
Returns false if validation fails.
If $form->ran_validation is true (should happen only if the form object stays in memory between requests), returns the cached validated result. is true. To force a re-validation call $form->clear.
Params may be passed in to validate, or else may be set earlier by passing into 'update_from_form' in the model, or using the params setter.
The method does the following:
1) sets required dependencies
2) trims params and saves in field 'input' attribute
3) calls the field's 'validate_field' routine which:
1) validates that required fields have a value
2) calls the field's 'validate' routine (the one that is provided
by custom field classes)
3) calls 'input_to_value' to move the data from the 'input' attribute
to the 'value' attribute if it hasn't happened already in 'validate'
4) calls the form's validate_$fieldname, if the method exists and
if there's a value in the field
5) calls cross_validate for validating fields that might be blank and
checking more complex dependencies. (If this field, then not that field...)
6) calls the model's validation method. By default, this only checks for
database uniqueness.
7) counts errors, sets 'ran_validation' and 'validated' flags
8) returns 'validated' flag
munge_params
Munges the parameters when they are set. Currently just adds keys without the "html_prefix". Can be subclassed.
dump_validated
For debugging, dump the validated fields.
cross_validate
This method is useful for cross checking values after they have been saved as their final validated value, and for performing more complex dependency validation.
This method is called even if some fields did not validate.
has_error
Returns true if validate has been called and the form did not validate.
has_errors
Checks the fields for errors and return true or false.
error_fields
Returns list of fields with errors.
error_field_name
Returns the names of the fields with errors.
errors
Returns a single array with all field errors
uuid
Generates a hidden html field with a unique ID which the model class can use to check for duplicate form postings.
AUTHOR
Gerda Shank, gshank@cpan.org
Based on the original source code of Form::Processor::Field by Bill Moseley
COPYRIGHT
This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.