[% # form_widgets.tt -- Bill Moseley (c) 2007 # # This is an example of how a template file can be used to generate the html # "widgets" needed to generate a form. There is no requirement to use this # template -- feel free to write the html directly in your own template. A # simple approach is often best. But, this is an example of how to automate # for generation using a template that deals with setting id and class # attributes and generating consistent error messages. # # # NOTE: This template calls "loc()" for localization of text. YOU MUST HAVE A # loc() subroutine in the stash for this template to function. If you don't # want to bother with I18N just create a sub in your stash: # # $stash->{loc} = sub { join ' ', @_ }; # # But that will not correctly format all messages since strings are # formatted for use with Locale::Maketext. # # To start a form call the form_wrapper block. This simply wraps # all the content in a
tag, summary of error messages, and a submit # button: # # WRAPPER form_wrapper; # PROCESS all_fields; # your block that generates form fields # END; # # The "add_fields" BLOCK would then insert the HTML form elements, text, layout # etc. This can be raw html or you can use macros provided by this template. # # The high-level macro "field()" is used to generate a form element that # is wrapped in a
, and includes any error messages for that field. # So your "add_field" BLOCK might look like: # # BLOCK add_fields; # '
'; # field( 'First name', 'first_name' ); # field( 'Last name', 'last_name' ); # field( 'Your email', 'email' ); # END; # # Those all require that there's a "form" stash element. Globals are ugly # but normally only working with on major form per request. # # Macros are used to generate the form items. At the finest detail are the # macros that create the html elements without any enclosing markup # but with ids and names automatically created: # # MACRO html_element_input( field, optional_input_type ); # MACRO html_element_textarea( field ); # # MACRO html_element_checkbox_group( field ); # MACRO html_element_select( field, add_heading ); # MACRO html_element_radio( field ); # # where "field" is either a field object or a field name of the form # in the "form" stash variable. # # The above html_element_* macros can be automatically selected via the macro: # # MACRO form_field_element( field ); # # But the selection of presentation is not always fixed -- that is, # for a "Select" or "Multiple" type of field checkboxes, radio groups, # or select/option lists will be used based on the number of options to # display. Also, if no options exist a message as such will be displayed. # # To generate a field