CONTENTS

NAME

HTML::FormHandler::Field - base class for fields

VERSION

version 0.40068

SYNOPSIS

Instances of Field subclasses are generally built by HTML::FormHandler from 'has_field' declarations or the field_list, but they can also be constructed using new for test purposes (since there's no standard way to add a field to a form after construction).

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

In your custom field class:

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

has 'my_attribute' => ( isa => 'Str', is => 'rw' );

apply [ { transform => sub { ... } },
        { check => ['fighter', 'bard', 'mage' ], message => '....' }
      ];
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 from the 'field_name_space' (or directly, when prefixed with '+'). If the type is not specified, it defaults to Text.

See HTML::FormHandler::Manual::Fields for a list of the fields and brief descriptions of their structure.

ATTRIBUTES

Names, types, accessor

name

The name of the field. Used in the HTML form. Often a db accessor. The only required attribute.

type

The class or type of the field. The 'type' of HTML::FormHandler::Field::Money is 'Money'. Classes that you define yourself are prefixed with '+'.

accessor

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

full_name

The name of the field with all parents:

'event.start_date.month'
full_accessor

The field accessor with all parents.

html_name

The full_name plus the form name if 'html_prefix' is set.

input_param

By default we expect an input parameter based on the field name. This allows you to look for a different input parameter.

Field data

inactive, is_inactive, is_active

Set the 'inactive' attribute to 1 if this field is inactive. The 'inactive' attribute that isn't set or is set to 0 will make a field 'active'. This provides a way to define fields in the form and selectively set them to inactive. There is also an '_active' attribute, for internal use to indicate that the field has been activated/inactivated on 'process' by the form's 'active'/'inactive' attributes.

You can use the is_inactive and is_active methods to check whether this particular field is active.

if( $form->field('foo')->is_active ) { ... }
input

The input string from the parameters passed in.

value

The value as it would come from or go into the database, after being acted on by inflations/deflations and transforms. Used to construct the $form->values hash. Validation and constraints act on 'value'.

See also HTML::FormHandler::Manual::InflationDeflation.

fif

Values used to fill in the form. Read only. Use a deflation to get from 'value' to 'fif' if an inflator was used. Use 'fif_from_value' attribute if you want to use the field 'value' to fill in the form.

[% form.field('title').fif %]
init_value

Initial value populated by init_from_object. You can tell if a field has changed by comparing 'init_value' and 'value'. Read only.

input_without_param

Input for this field if there is no param. Set by default for Checkbox, and Select, since an unchecked checkbox or unselected pulldown does not return a parameter.

Form, parent

form

A reference to the containing form.

parent

A reference to the parent of this field. Compound fields are the parents for the fields they contain.

Errors

errors

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

add_error

Add an error to the list of errors. Error message will be localized using '_localize' method. See also HTML::FormHandler::TraitFor::I18N.

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

Compound fields will have an array of errors from the subfields.

localize_meth

Set the method used to localize.

Attributes for creating HTML

The 'element_attr' hashref attribute can be used to set arbitrary HTML attributes on a field's input tag.

has_field 'foo' => ( element_attr => { readonly => 1, my_attr => 'abc' } );

Note that the 'id' and 'type' attributes are not set using element_attr. Use the field's 'id' attribute (or 'build_id_method') to set the id.

The 'label_attr' hashref is for label attributes, and the 'wrapper_attr' is for attributes on the wrapping element (a 'div' for the standard 'simple' wrapper).

A 'javascript' key in one of the '_attr' hashes will be inserted into the element as-is.

The following are used in rendering HTML, but are handled specially.

label       - Text label for this field. Defaults to ucfirst field name.
build_label_method - coderef for constructing the label
wrap_label_method - coderef for constructing a wrapped label
id          - Useful for javascript (default is html_name. to prefix with
              form name, use 'html_prefix' in your form)
build_id_method - coderef for constructing the id
render_filter - Coderef for filtering fields before rendering. By default
              changes >, <, &, " to the html entities
disabled    - Boolean to set field disabled

The order attribute may be used to set the order in which fields are rendered.

order       - Used for sorting errors and fields. Built automatically,
              but may also be explicitly set

The following are discouraged. Use 'element_attr', 'label_attr', and 'wrapper_attr' instead.

title       - instead use element_attr => { title => '...' }
style       - instead use element_attr => { style => '...' }
tabindex    - instead use element_attr => { tabindex => 1 }
readonly    - instead use element_attr => { readonly => 'readonly' }

Rendering of the various HTML attributes is done by calling the 'process_attrs' function (from HTML::FormHandler::Render::Util) and passing in a method that adds in error classes, provides backward compatibility with the deprecated attributes, etc.

attribute hashref  class attribute        wrapping method
=================  =================      ================
element_attr       element_class          element_attributes
label_attr         label_class            label_attributes
wrapper_attr       wrapper_class          wrapper_attributes
                   element_wrapper_class  element_wrapper_attributes

('element_wrapper' is for an inner div around the input element, not including the label. Used for Bootstrap3 rendering, but also available in the Simple wrapper.) The slots for the class attributes are arrayrefs; they will coerce a string into an arrayref. In addition, these 'wrapping methods' call a hook method in the form class, 'html_attributes', which you can use to customize and localize the various attributes. (Field types: 'element', 'wrapper', 'label')

sub html_attributes {
    my ( $self, $field, $type, $attr ) = @_;
    $attr->{class} = 'label' if $type eq 'label';
    return $attr;
}

The 'process_attrs' function will also handle an array of strings, such as for the 'class' attribute.

tags

A hashref containing flags and strings for use in the rendering code. The value of a tag can be a string, a coderef (accessed as a method on the field) or a block specified with a percent followed by the blockname ('%blockname').

Retrieve a tag with 'get_tag'. It returns a '' if the tag doesn't exist.

This attribute used to be named 'widget_tags', which is deprecated.

html5_type_attr [string]

This string is used when rendering an input element as the value for the type attribute. It is used when the form has the is_html5 flag on.

widget

The 'widget' attribute is used in rendering, so if you are not using FormHandler's rendering facility, you don't need this attribute. It is used 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. If you want a new widget type, create a widget role, such as MyApp::Form::Widget::Field::MyWidget. Provide the name space in the 'widget_name_space' attribute, and set the 'widget' of your field to the package name after the Field/Form/Wrapper:

has_field 'my_field' => ( widget => 'MyWidget' );

If you are using a template based rendering system you will want to create a widget template. (see HTML::FormHandler::Manual::Templates)

Widget types for some of the provided field classes:

Widget                 : Field classes
-----------------------:---------------------------------
Text                   : Text, Integer
Checkbox               : Checkbox, Boolean
RadioGroup             : Select, Multiple, IntRange (etc)
Select                 : Select, Multiple, IntRange (etc)
CheckboxGroup          : Multiple select
TextArea               : TextArea
Compound               : Compound, Repeatable, DateTime
Password               : Password
Hidden                 : Hidden
Submit                 : Submit
Reset                  : Reset
NoRender               :
Upload                 : Upload

Widget roles are automatically applied to field classes unless they already have a 'render' method, and if the 'no_widgets' flag in the form is not set.

You can create your own widget roles and specify the namespace in 'widget_name_space'. In the form:

has '+widget_name_space' => ( default => sub { ['MyApp::Widget'] } );

If you want to use a fully specified role name for a widget, you can prefix it with a '+':

widget => '+MyApp::Widget::SomeWidget'

For more about widgets, see HTML::FormHandler::Manual::Rendering.

Flags

password  - prevents the entered value from being displayed in the form
writeonly - The initial value is not taken from the database
noupdate  - Do not update this field in the database (does not appear in $form->value)

Defaults

See also the documentation on "Defaults" in HTML::FormHandler::Manual::Intro.

default_method, set_default

Supply a coderef (which will be a method on the field) with 'default_method' or the name of a form method with 'set_default' (which will be a method on the form). If not specified and a form method with a name of default_<field_name> exists, it will be used.

default

Provide an initial value just like the 'set_default' method, except in the field declaration:

has_field 'bax' => ( default => 'Default bax' );

FormHandler has flipped back and forth a couple of times about whether a default specified in the has_field definition should override values provided in an initial item or init_object. Sometimes people want one behavior, and sometimes the other. Now 'default' does *not* override.

If you pass in a model object with item => $row or an initial object with init_object => {....} the values in that object will be used instead of values provided in the field definition with 'default' or 'default_fieldname'. If you want defaults that override or supplement the item/init_object, you can use the form flags 'use_defaults_over_obj', 'use_init_obj_over_item', and 'use_init_obj_when_no_accessor_in_item'.

You could also put your defaults into your row or init_object instead.

default_over_obj

This is deprecated; look into using 'use_defaults_over_obj' or 'use_init_obj_over_item' flags instead. They allow using the standard 'default' attribute.

Allows setting defaults which will override values provided with an item/init_object. (And only those. Will not be used for defaults without an item/init_object.)

has_field 'quux' => ( default_over_obj => 'default quux' );

At this time there is no equivalent of 'set_default', but the type of the attribute is not defined so you can provide default values in a variety of other ways, including providing a trait which does 'build_default_over_obj'. For examples, see tests in the distribution.

Constraints and Validations

See also HTML::FormHandler::Manual::Validation.

Constraints set in attributes

required

Flag indicating whether this field must have a value

unique

For DB field - check for uniqueness. Action is performed by the DB model.

messages
messages => { required => '...', unique => '...' }

Set messages created by FormHandler by setting in the 'messages' hashref. Some field subclasses have additional settable messages.

required: Error message text added to errors if required field is not present. The default is "Field <field label> is required".

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,
}
not_nullable

Fields that contain 'empty' values such as '' are changed to undef in the validation process. If this flag is set, the value is not changed to undef. If your database column requires an empty string instead of a null value (such as a NOT NULL column), set this attribute.

has_field 'description' => (
    type => 'TextArea',
    not_nullable => 1,
);

This attribute is also used when you want an empty array to stay an empty array and not be set to undef.

It's also used when you have a compound field and you want the 'value' returned to contain subfields with undef, instead of the whole field to be undef.

apply

Use the 'apply' keyword to specify an ArrayRef of constraints and coercions to be executed on the field at validate_field time.

has_field 'test' => (
   apply => [ 'MooseType',
              { check => sub {...}, message => { } },
              { transform => sub { ... lc(shift) ... } }
            ],
);

See more documentation in HTML::FormHandler::Manual::Validation.

trim

An action to trim the field. By default this contains a transform to strip beginning and trailing spaces. Set this attribute to null to skip trimming, or supply a different transform.

trim => { transform => sub {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
} }
trim => { type => MyTypeConstraint }

Trimming is performed before any other defined actions.

Inflation/deflation

There are a number of methods to provide finely tuned inflation and deflation:

inflate_method

Inflate to a data format desired for validation.

deflate_method

Deflate to a string format for presenting in HTML.

inflate_default_method

Modify the 'default' provided by an 'item' or 'init_object'.

deflate_value_method

Modify the value returned by $form->value.

deflation

Another way of providing a deflation method.

transform

Another way of providing an inflation method.

Normally if you have a deflation, you will need a matching inflation. There are two different flavors of inflation/deflation: one for inflating values to a format needed for validation and deflating for output, the other for inflating the initial provided values (usually from a database row) and deflating them for the 'values' returned.

See HTML::FormHandler::Manual::InflationDeflation.

Processing and validating the field

validate_field

This is the base class validation routine. Most users will not do anything with this. It might be useful for method modifiers, if you want code that executed before or after the validation process.

validate

This field method can be used in addition to or instead of 'apply' actions in custom field classes. It should validate the field data and set error messages on errors with $field->add_error.

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

validate_method, set_validate

Supply a coderef (which will be a method on the field) with 'validate_method' or the name of a form method with 'set_validate' (which will be a method on the form). If not specified and a form method with a name of validate_<field_name> exists, it will be used.

Periods in field names will be replaced by underscores, so that the field 'addresses.city' will use the 'validate_addresses_city' method for validation.

has_field 'my_foo' => ( validate_method => \&my_foo_validation );
sub my_foo_validation { ... }
has_field 'title' => ( isa => 'Str', set_validate => 'check_title' );

AUTHOR

FormHandler Contributors - see HTML::FormHandler

COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Gerda Shank.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.