NAME

HTML::FormHandler::Field - Base class for HTML::FormHandler Fields

SYNOPSIS

Instances of Field subclasses are generally built by HTML::FormHandler from the field_list, but they can also be constructed using new.

use HTML::FormHandler::Field::Text;
my $field = HTML::FormHandler::Field::Text->new( name => $name, ... );

In your custom field class:

package MyApp::Field::MyText;
extends 'HTML::FormHandler::Field::Text';

has 'my_attribute' => ( isa => 'Str', is => 'rw' );
sub validate { ... }
1;

DESCRIPTION

This is the base class for form fields. The 'type' of a field class is used in the FormHandler field_list or has_field to identify which field class to load.

A number of field classes are provided by the distribution. The basic field types are:

Text
Integer
Select
Boolean

These field types alone would be enough for most applications, since the equivalent of the others could be defined using field attributes and custom validation methods. There is some benefit to having descriptive names, of course, and if you have multiple fields requiring the same validation, you should certainly define a custom field class.

Inheritance hierarchy of the distribution's field classes:

Text
   Money
   Password
   Integer
      PosInteger
TextArea
   HtmlArea
Select
   Multiple
   IntRange
      Hour
      Minute
      MonthDay
      Month
      Second
      Year
   MonthName 
   Weekday
      WeekdayStr
Boolean
   Checkbox
DateMDY
DateTime
Email
   

See the documentation or source for the individual fields.

Normally you would implement a 'validate' routine in a custom field class, but you can also override the base validation process by overriding 'process'.

ATTRIBUTES

name

Field name. If this is a database form, this name is usually a database column/accessor name or relationship.

type

Field type (e.g. 'Text', 'Select' ... ) from a HTML::FormHandler::Field subclass, either one provided in the distribution or one that you create yourself, proceded by a "+": type => '+MetaText'

init_value

Initial value populated by init_from_object. You can tell if a field has changed by comparing 'init_value' and 'value'. Not to be confused with the form method init_value(). Not set by user.

value

The initial value of the field from the database (or init_object), and the changed value after form validation. A change in this attribute triggers setting the 'fif' attribute.

The "validate" field method usually sets this value if the field validates.

The user does not need to set this field except in validation methods.

parent

A reference to the parent of this field.

errors_on_parent

Flag indicating that errors should not be set on this field class

input

Input value for the field, moved from the parameter hash. In HTML::FormHandler, the setter for this attribute is for internal use. If you want to set an input value, use the 'set_param' method. A field validation routine may copy the value of this attribute to the 'value' attribute. The setter may be used in field tests and if a field class is used standalone. A change in this attribute triggers setting 'fif'.

input_without_param

Input for this field if there is no param. Needed for checkbox, since an unchecked checkbox does not return a parameter.

fif

For filling in forms. Input or value. The user does not need to set this field. It is set by FormHandler from the values in your database object or the input parameters. The normal use would be to access this field from a template:

[% f = form.field('title') %]
[% f.fif %]

accessor

If the name of your field is different than your database accessor, use this attribute to provide the name of accessor.

temp

Temporary attribute. Not used by HTML::FormHandler.

label

Text label for this field. Useful in templates. Defaults to ucfirst field name.

title

Place to put title for field, for mouseovers. Not used by F::P.

style

Field's generic style to use for css formatting in templates. Not actually used by F::P.

css_class

Field's css_class for use in templates.

sub_form

The field is made up of a sub-form.

A single field can be represented by multiple sub-fields contained in a form. This is a reference to that form.

form

A reference to the containing form.

prename

Field name prefixed by the form name and a dot. A field named "street" in a form named "address" would have a prename of "address.street". Use with the form attribute "html_prefix". Allows multiple forms with the same field names.

widget

The 'widget' is attribute is not used by base FormHandler code. It is intended for use in generating HTML, in templates and the rendering roles. Fields of different type can use the same widget.

This attribute is set in the field classes, or in the fields defined in the form.

Widget types for the provided field classes:

Widget      : Field classes 
------------:-----------------------------------
text        : Text, Integer
checkbox    : Checkbox, Select
radio       : Boolean, Select
select      : Select, Multiple
textarea    : TextArea, HtmlArea
compound    : DateTime
password    : Password

The 'Select' field class has a 'select_widget' method that chooses which widget to use, which could be called by templates or rendering roles.

The default widget is 'text'.

order

This is the field's order used for sorting errors and field lists. See the "set_order" method and F::P method "sorted_fields". The order field is set for the fields when the form is built, but if the fields are defined with a hashref the order will not be defined. The "auto" and "fields" field_list attributes will take an arrayref which will preserve the order. If you explicitly set "order" on the fields in a field_list, you should set it on all the fields, otherwise results will be unpredictable.

required

Flag indicating whether this field must have a value

required_message

Error message text added to errors if required field is not present

The default is "Field <field label> is required".

unique

Flag to initiate checks in the database model for uniqueness.

unique_message

Error message text added to errors if field is not unique

range_start

range_end

Field values are validated against the specified range if one or both of range_start and range_end are set and the field does not have 'options'.

The IntRange field uses this range to create a select list with a range of integers.

In a FormHandler field_list

age => {
    type            => 'Integer',
    range_start     => 18,
    range_end       => 120,
}

Or just set one:

age => {
    type            => 'Integer',
    range_start     => 18,
}

Range checks are done after validation so must only be used on appropriate fields

id, build_id

Provides an 'id' for the field. Useful for javascript. The default id is:

$field->form->name . $field->id

Override with "build_id".

javascript

Store javascript for the field

password

This is a boolean flag to prevent the field from being returned in the $form-fif> and $field-fif> methods.

writeonly

Fields flagged 'writeonly' are not returned in the 'fif' methods from the field's initial value, even if a value for the field exists in the item. The value is not read from the database. However, the value entered into the form WILL be returned. This might be used for columns that should only be written to the database on updates.

clear

This is a flag that says you want to set the database column to null for this field. Validation is also not run on this field.

disabled

readonly

These allow you to enter hints about how the html element is generated.

HTML::FormHandler does not use these attributes; they are for your convenience in constructing HTML.

noupdate

This boolean flag indicates a field that should not be updated. Fields flagged as noupdate are skipped when processed by the model.

This is useful when a form contains extra fields that are not directly written to the data store.

errors

Returns the error list for the field. Also provides 'num_errors', 'has_errors', 'push_errors' and 'clear_errors' from Collection::Array metaclass. Use 'add_error' to add an error to the array if you want to use a MakeText language handle. Default is an empty list.

set_validate

Specify the form method to be used to validate this field. The default is 'validate_' . $field->name. (Periods in field names will be changed to underscores.) If you have a number of fields that require the same validation and don't want to write a field class, you could set them all to the same method name.

has_field 'title' => ( isa => 'Str', set_validate => 'check_title' );
has_field 'subtitle' => ( isa => 'Str', set_validate => 'check_title' );

set_init

The name of the method in the form that provides a field's initial value

apply

An ArrayRef of constraints and coercions to be executed on the field at process time. In general the action can be of three types: a Moose type (which is represented by it's name), a transformation (which is a callback called on the value of the field), or a constraint which performes a 'smart match' on the value of the field. Currently we implement the smart match in our code - but in the future when Perl 5.10 is more widely used we'll switch to the core http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perlsyn.pod#Smart_matching_in_detail smart match operator. The Moose type action first tries to coerce the value - then it checks the result, so you can use it instead of both constraints and tranformations - TIMTOWTDI.

Examples:

A Moose type: subtype 'MyStr' => as 'Str' => where { /^a/ };

This is a simple constraint checking if the value string starts with the letter 'a'.

Another Moose type: subtype 'MyInt' => as 'Int'; coerce 'MyInt' => from 'MyStr' => via { return $1 if /(\d+)/ };

This type contains a coercion.

You can use them in a field like this:

has_field 'some_text_to_int' => (
    apply => [ 'MyStr', 'MyInt' ]
);

This will check if the field contains a string starting with 'a' - and then coerce it to an integer by extracting the first continues string of digits.

A simple constraint:

has_field 'some_text' => (
    apply => [ { check => qr/aaa/, message => 'Must contain aaa' } ],
);

This should be self-explanatory.

And a simple transformation:

has_field 'sprintf_filter' => (
    apply => [ { transform => sub{ sprintf '<%.1g>', $_[0] } } ]
);

As you can see above, all three types define a message to be presented to the user in the case of failure. Transformations and coercions are called in an eval to catch the errors.

All the actions are called in the order that they are defined, so that you can check constraints after transformations and vice versa. You can weave all three types of actions in any order you need.

METHODS

new [parameters]

Create a new instance of a field. Initial values are passed as a list of parameters.

full_name

This returns the name of the field, but if the field is a child field will prepend the field with the parent's field name. For example, if a field is "month" and the parent's field name is "birthday" then this will return "birthday.month".

set_order

This sets the field's order to the form's field_counter and increments the counter. This may be used in a template when displaying the field.

add_error

Add an error to the list of errors. If $field->form is defined then process error message as Maketext input. See $form->language_handle for details. Returns undef.

return $field->add_error( 'bad data' ) if $bad;

process

This method does standard validation, which currently tests:

required        -- if field is required and value exists

Then if a value exists, calls the 'augment' validate_field method in subclasses.

If these tests pass, the field's validate method is called

$field->validate;

If $field->validate returns true then the input value is copied from the input attribute to the field's value attribute.

The field's error list and internal value are reset upon entry.

validate

This method validates the input data for the field and returns true if the data validates. An error message must be added to the field with $field->add_error( ... ) if the value does not validate. The default method is to return true.

sub validate {
    my $field = shift;
    my $input = $field->input;
    return $field->add_error( ... ) if ( ... );
    return 1;
}

test_ranges

If range_start and/or range_end is set AND the field does not have options will test that the value is within range. This is called after all other validation.

input_defined

Returns true if $self->input contains any non-blank input.

value_changed

Returns true if the value in the item has changed from what is currently in the field's value.

This only does a string compare (arrays are sorted and joined).

required_text

Returns "required" or "optional" based on the field's setting.

dump_field

A little debugging.

AUTHORS

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.