HTML::Forms - HTML forms using Moo
my $form = HTML::Forms->new_with_traits(
name => 'test_tt', traits => [ 'HTML::Forms::Role::Defaults' ],
);
$form->render;
Generates markup for and processes input from HTML forms. This is a Moo based copy of HTML::FormHandler
Files wcom-*.js are included in the share/js directory of the source
tree. These will be installed to the File::ShareDir distribution level
shared data files. Nothing further is done with these files. They should be
concatenated in sort order by filename and the result placed under the
webservers document root. Link to this from the web applications pages. Doing
this is outside the scope of this distribution
When content is loaded the JS method WCom.Form.Renderer.scan(content) must
be called to inflate the otherwise empty HTML div element if the front end
rendering class is being used. The function
WCom.Util.Event.onReady(callback) is available to install the scan when the
page loads
A file hforms-minimal.less is included in the share/less directory
of the source tree. This will be installed to File::ShareDir distribution
level shared data files. Nothing further is done with this file. It would need
compiling using the Node.js LESS compiler to produce a CSS file which should be
placed under the web servers document root and then linked to in the header of
the web applications pages. This is outside the scope of this distribution
Defines the following attributes;
-
Mutable booleans defaulting false
- did_init_obj - True when the result has been initialised
- do_form_wrapper - If true wraps the form in a containing element
- do_label_colon - If true a colon is appended to the label
- do_label_colon_right - If true place the label colon on the right
- do_label_right - If true place the label on the right if the field
- processed - True when the form has been processed
- render_js_after - If true render the JS after the form
- use_init_obj_when_no_accessor_in_item - Self describing
- verbose - When true emits diagnostics on stderr
-
Immutable booleans defaulting false
- html_prefix - If true the form name is prepended to field names
- is_html5 - If true apply HTML5 attributes to fields
- messages_before_start - If true display messages before the form start
- no_preload - If the true the result is not initialised on build
- no_widgets - If true widget roles are not applied to the form
- quote_bind_value - If true quote the bind values in messages
-
action
URL for the action attribute on the form. A mutable string with no default
-
active
A mutable array reference of active field names with an empty default
Handles;
add_active,clear_active, andhas_activevia the array trait -
context
An optional mutable weak reference to the context object
-
clear_context
Clearer
-
has_context
Predicate
-
default_locale
If
contextis provided and has aconfigobject use it'slocaleattribute, otherwise default toen. An immutable lazy string used as the default language in building thelanguage_handle -
defaults
A mutable hash reference of default values keyed by field name. These are applied to the field when the form is setup overriding the default value in the field definition
Handles;
clear_defaultsandhas_defaultsvia the hash trait -
dependency
A mutable array reference of array references. Each inner reference should contain two or more field names. If the first named field has a value then the subsequent fields are required
-
enctype
A mutable string without default. Sets the encoding type on the form element
-
error_message
A mutable string without default. This string (if set) is rendered either before or near the start of the form if the form result
has_errorsorhas_form_errors -
clear_error_messsage
Clearer
-
has_error_message
Predicate
-
field_traits
A lazy immutable array reference with an empty default. This list of
HTML::Forms::Widget::Field::Traitroles are applied to all fields on the formHandles;
add_field_traitandhas_field_traitsvia the array trait -
for_js
A mutable hash reference with an empty default. Provides support for the
Repeatablefield type. Keyed by the repeatable field name contains a data structure used by the JS event handlers to add/remove repeatable fields to/from the form. Populated automatically by theRepeatablefield typeHandles;
clear_for_js,has_for_js, andset_for_jsvia the hash trait -
form_element_attr
A mutable hash reference with an empty default. Attributes and values applied to the form element
Handles;
delete_form_element_attr,exists_form_element_attr,get_form_element_attr,has_form_element_attr, andset_form_element_attrvia the hash trait -
form_element_class
A mutable array reference of strings with an empty default. List of classes to apply to the form element
Handles
has_form_element_classvia the array trait -
form_wrapper_attr
A mutable hash reference with an empty default. Attributes and values applied to the form wrapper
Handles;
delete_form_wrapper_attr,exists_form_wrapper_attr,get_form_wrapper_attr,has_form_wrapper_attr, andset_form_wrapper_attrvia the hash trait -
form_wrapper_class
A mutable array reference of strings with an empty default. List of classes to apply to the form wrapper
Handles
has_form_wrapper_classvia the array trait -
form_tags
An immutable hash reference with an empty default. The optional tags are applied to the form HTML. Keys used;
after- Markup rendered at the very end of the formafter_start- Markup rendered after the form has been startedbefore- Markup rendered at the start before the formbefore_end- Markup rendered before the end of the formerror_class- Error message class. Defaults toalert alert-severeinfo_class- Info message class. Defaults toalert alert-infolegend- Content for the form's legendmessages_wrapper_class- Defaults toform-messagesno_form_messages- If true no form messages will be renderedsuccess_class- Defaults toalert alert-successwrapper_tag- Tag to wrap the form in. Defaults tofieldset
The keys that contain markup are only implemented by the Template Toolkit renderer
Handles;
has_tag,set_tag, andtag_existsvia the hash traitSee get_tag
-
http_method
An immutable string with a default of
post. The method attribute on the form element -
inactive
A mutable array reference of inactive field names with an empty default
Handles;
add_inactive,clear_inactive, andhas_inactivevia the array trait -
index
An immutable hash reference of field objects with an empty default. Provides an index by field name to the field objects in the fields array
Handles;
add_to_index,field_from_index, andfield_in_indexvia the hash trait -
info_message
A mutable string with no default. The information message to display at the start of the form
-
clear_info_message
Clearer
-
has_info_message
Predicate
-
init_object
A lazy untyped mutable attribute with no default. If
itemis not set and this attribute is, it will be used to initialise theresultobject -
clear_init_object
Clearer
-
language_handle
A lazy object built by
build_language_handle. An instance oflanguage_handle_classit is used to translate text into different languages via the calls tomaketext -
language_handle_class
A lazy loadable class which defaults to HTML::Forms::I18N. The name of the class which implements language translation. Expected to be a subclass of Locale::Maketext
-
locales
A lazy immutable array reference of strings. Defaults to the
localeson therequestobject if available, empty otherwise -
has_locales
Predicate
-
messages
A mutable hash reference of string with an empty default. If set these messages will be used in preference to class messages by the
get_messagemethod on the field objectHandles;
set_messagevia the hash trait -
name
A mutable string with a random default. The name of the form element
-
no_update
A mutable bool without default. If set to true the call in
processto update the model will be skipped -
clear_no_update
Clearer
-
params
A mutable hash reference with an empty default. Should be set to the keys and values of the form when it is posted back. Parameters are munged by the trigger. See HTML::Forms::Params
Handles;
clear_params,get_param,has_params, andset_paramvia the hash trait -
params_args
An immutable array reference with an empty default. Arguments passed to the HTML::Forms::Params constructor
-
posted
A mutable boolean without default. Should be set to true if the form was posted
-
clear_posted
Clearer
-
has_posted
Predicate
-
renderer
A lazy immutable instance of the
renderer_classwhich handles therendermethod -
renderer_args
An immutable hash reference passed to the constructor of the
rendererobject empty by default -
renderer_class
A lazy loadable class which defaults to HTML::Forms::Render::WithTT. The class name of the
rendererobject. Set to HTML::Forms::Render::EmptyDiv form rendering will by done by JS in the browser -
result
An lazy immutable HTML::Forms::Result object constructed by the
build_resultmethodHandles;
add_result,all_form_errors,clear_form_errors,form_errors,has_form_errors,has_input,has_value,input,is_valid,num_form_errors,push_form_errors,ran_validation,results,validated, andvalue -
clear_result
Clearer
-
has_result
Predicate
-
style
A mutable string with no default. If set this is applied as the
styleattribute of the form -
success_message
A mutable string with no default. If set this is displayed near the start of the form
-
clear_success_message
Clearer
-
has_success_message
Predicate
-
title
An immutable string with no default. If set and HTML::Forms::Role::Defaults is applied to the form class this string will be used as the form legend
-
update_field_list
A mutable hash reference with an empty default. If set the keys are field names an the values are hash references of field attribute names and values. This will be applied to the fields in the form when
setup_formis calledHandles;
clear_update_field_list,has_update_field_list, andset_update_field_listvia the hash trait -
use_defaults_over_obj
A mutable boolean without default. If true will use the defaults on the field definition in preference to the
itemobject -
clear_use_defaults_over_obj
Clearer
-
use_fields_for_input_without_param
A mutable boolean without default. Changes how the field object instantiates the result object
-
use_init_obj_over_item
A mutable boolean which defaults false. If true the
init_objectis used in preference to theitemwhen initialising theresultobject -
clear_use_init_obj_over_item
Clearer
-
widget_form
An immutable string which defaults to
Simple. If set toComplexthen the HTML::Forms::Role::Widget::Form::Complex role will be applied to the form and result objects -
widget_name_space
An immutable array reference of string with an empty default. Additional name spaces to be search when looking for widget roles
Handles;
add_widget_name_spacevia the array trait -
widget_wrapper
An immutable string which defaults to
Simple. Adds arendermethod to the field object
Defines the following methods;
-
BUILDARGS
Additionally allows for construction from either an
itemobject instance or anitem_id -
BUILD
Applies widget roles, builds the fields, sets the active field list, and initialises the result object. Will also dump the field definitions if
verboseis trueThe methods
before_build_fields, andafter_build_fieldsare called either side of the above and are dummy methods in this class. Made for overriding in a form role -
add_form_element_class
$class = $self->add_form_element_class( @args );Takes either an array reference of a list. Pushes onto the
form_elementclass list -
add_form_error
$self->add_form_error( @message );Pushes the supplied message (after localising) onto form errors. Uses the
form is invalidmessage if one is not supplied -
add_form_wrapper_class
$class = $self->add_form_wrapper_class( @args );Takes either an array reference of a list. Pushes onto the
form_wrapperclass list -
after_build_fields
Dummy method called by
BUILD. Expected to be decorated in the form classes -
after_update_model
Called after the the call to
update_model. Return without doing anything unless wehas_repeatable_fieldsand we also has anitem. This an attempt to reload the repeatable relationships after the database is updated, so that we get the primary keys of the repeatable elements. Otherwise, if a form is re-presented, repeatable elements without primary keys may be created again. There is no reliable way to connect up existing repeatable elements with their db-created primary keys. -
attributes
A proxy for
form_element_attributes -
before_build_fields
Dummy method called at the start of the
BUILDmethod. Expected to be decorated in the form classes -
build_active
Called at build time it clears the inactive status of any
activefields and sets the inactive status on anyinactivefields -
build_errors
Moves the errors to the
resultobject -
build_language_handle
Constructor for the
language_handleattribute. Will uselocalesif available otherwise uses the environment variableLANGUAGE_HANDLE. Always appendsdefault_localeto the list supplied to thelanguage_handle_class'sget_handleconstructor method -
build_result
Builds the
resultobject an instance of HTML::Forms::Result -
clear
Calls all the clearers defined on the form object. Sets
processedanddid_init_objto false -
fif$hash = $self->fif( @args );Fill in form. Returns a hash reference whose keys are the field names and whose values are take from the result
-
form
Returns the self referential object
-
form_element_attributes
Returns a hash reference of keys and values which are applied to the form element
Also calls
html_attributeswith a 'type' of 'form_element' returning it's returned hash reference if set. Allows for an overriddenhtml_attributesto "fix things up" if required -
form_wrapper_attributes
Returns a hash reference of keys and values which are applied to the form wrapper element
Also calls
html_attributeswith a 'type' of 'form_wrapper' returning it's returned hash reference if set. Allows for an overriddenhtml_attributesto "fix things up" if required -
full_accessor
Dummy method returns the null string
-
full_name
Dummy method returns the null string
-
get_default_value
Dummy method returns nothing
-
get_tag
$tag_string = $self->get_tag( $name );Returns the
forms_tagsentry for the given name if it exists, otherwise returns null. Code references a called as a method and their values are returned. If the tag begins with a%and the following word is a namedblockcall the blocks render method and return that. Return null otherwise -
has_flag
$bool = $self->has_flag( $flag_name );If the form object has a method
flag_namecall it and return it's value. Return undef otherwise -
html_attributes
$attrs = $self->html_attributes( $object, $type, $attrs, $result );Dummy method that returns the supplied
attrs. Called byform_element_attributes. Thetypeargument is one of; 'element', 'element_wrapper', 'form_element', 'form_wrapper', 'label', or 'wrapper'.Applied roles can modify this method to alter the attributes of the above list of form elements
-
init_value
$self->init_value( $field, $value );Sets both the initial and current field values to the one supplied
-
localise
$message = $self->localise( $message, @args );Calls
maketexton thelanguage_handleto localise the supplied message. If localisation fails will substitute the placeholder variables and return that string -
new_with_traits
$form = $self->new_with_traits( %args );Either a class or object method. Returns a new instance of this class with the list of supplied
traitsin theargshash applied. This rest of theargshash is supplied to the constructor of the new object -
process
$validated = $self->process( @args );Calls clear if processed is true. Calls setup_form with the supplied
@args. If the form was posted calls validate_form. If validated is true and no_update is false call both update_model and then after_update_model. Set processed to true and return validatedConsider this fragment from a controller/model method that processes a form
GETorPOST. It stashes the form object (for rendering in the HTML template) and if posted successfully stashes a redirect to the give action path with a message that should be displayed to the usermy $form = $self->new_form('form_name', { context => $context }); if ($form->process( posted => $context->posted )) { my $location = $context->uri_for_action('action/path'); my $message = 'Show this to the user'; $context->stash(redirect $location, [$message]); return; } $context->stash(form => $form); -
set_active
Set active fields to
activeand inactive fields toinactive -
setup_form
$self->setup_form( @args );Called from process. The
@argsis either a hash reference or a list of keys and values. The hash reference is used to instantiate theparamshash reference, the list is used to set attributes on the form object. build_item is called if we have anitem_idand noitem. Theresultobject is cleared, fields have their activation state set, update_fields is called,postedis set to true if we hasparamsandpostedwasn't supplied to the constructor. Theresultis initialised. Ifpostedthe result is cleared again and then initialised from theparamsprovided -
update_field
$self->update_field( $field_name, $updates );Updates the named field's attributes using the keys and values provided in the
updateshash reference -
update_fields
Called from process. If we
has_update_field_listcallupdate_fieldfor each element in the list. If wehas_defaultscallupdate_fieldsupplying those defaults -
validate
Dummy method which always returns true. Decorate this method from the form class, it is called from validate_form
-
validate_form
Called from process if the form was posted. Sets required dependencies, validates individual fields, calls the above
validatemethod, calls "validate_model" in HTML::Forms::Model, sets field values, builds any errors, clears the dependencies, clearsposted, setsran_validationto true and returns thevalidatedattribute -
values
Returns "value" in HTML::Forms::Result
Setting verbose to true will output diagnostic
information to stderr
There are no known incompatibilities in this module
There are no known bugs in this module. Please report problems to http://rt.cpan.org/NoAuth/Bugs.html?Dist=HTML-Forms. Patches are welcome
Larry Wall - For the Perl programming language
Gerda Shank gshank@cpan.org - Author of HTML::FormHandler of which this is a Moo based copy
Peter Flanigan, <pjfl@cpan.org>
Copyright (c) 2024 Peter Flanigan. All rights reserved
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic
This program is distributed in the hope that it will be useful, but WITHOUT WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE