Difference between revisions of "CGI::FormMagick"
(→AUTHOR) |
|||
Line 344: | Line 344: | ||
More information about FormMagick may be found at http://sourceforge.net/projects/formmagick/ | More information about FormMagick may be found at http://sourceforge.net/projects/formmagick/ | ||
− | |||
[[Category:SME Server Development Framework]] | [[Category:SME Server Development Framework]] | ||
[[Category:Development Tools]] | [[Category:Development Tools]] | ||
[[Category:SME9-Development]] | [[Category:SME9-Development]] |
Revision as of 22:19, 21 December 2013
NAME
CGI::FormMagick - easily create CGI form-based applications
In a root terminal you can do the command below if you want to display the up-to-date content
perldoc CGI::FormMagick
SYNOPSIS
use CGI::FormMagick; my $f = new CGI::FormMagick();
- all options available to new()
my $f = new CGI::FormMagick( type => file, source => $myxmlfile, );
- other types available
my $f = new CGI::FormMagick(type => string, source => $data ); $f->display();
DESCRIPTION
FormMagick is a toolkit for easily building fairly complex form-based web applications. It allows the developer to specify the structure of a multi-page "wizard" style form using XML, then display that form using only a few lines of Perl.
How it works:
You (the developer) provide at least:
- An XML form description
- HTML templates for the page headers and footers
And may optionally provide:
- Translations of strings used in your application, for localisation
- Validation routines for user input data
- Routines to run before or after a page of the form is displayed
FormMagick brings them all together to create a full application.
METHODS
new()
The "new()" method requires no arguments, but may take the following optional arguments (as a hash):
type
Defaults to "file". "string" is also available, in which case you must specify a source which is either a literal string or a scalar variable.
source
Defaults to a filename matching that of your script, only with an extension of .xml (we got this idea from XML::Simple).
charset
Tell FormMagick that the XML input uses the specified character set encoding. Defaults to ’none’ which is good enough for English text and US ASCII. Any other characters may cause parse errors. Valid charsets are "ISO-8859-1", "UTF-8", "UTF-16", or "US-ASCII". This option is case sensitive.
sessiondir
Defaults to the CGI::FormMagick default session directory. This can be set to override where the CGI::Persistent sessions are stored.
cgi
Defaults to a new CGI::Persistent object that uses the sessiondir directory. You can instead pass in your own cgi object provided that it inherits from CGI::Persistent. If you pass in your own cgi object, the sessiondir parameter will be ignored, and the ses siondir member of the cgi object will be used instead.
debug
Defaults to 0. Set this to 1 if you want FormMagick to print debug messages in the web page.
previousbutton()
With no arguments, tells you whether the previousbutton will be displayed or not. If you give it a true argument (eg 1) it will set the previous button to be displayed. A false value (eg 0) will set it to not be displayed.
nextbutton()
As for previousbutton, but affects the "Next" button.
finishbutton()
Ditto.
resetbutton()
Ditto.
startoverlink()
Ditto.
debug()
Turns debugging on/off.
fallback_language($language)
Given a 2-letter ISO language code, makes that language the fallback language for localisation. Not necessary unless you want it to be something other than the base language in which your application is written. Set it to a false (but defined) value to turn off the fall back language feature. With no arguments, tells you what the current fallback language is.
display()
The display method displays your form. It takes no arguments. It does however, respect certain CGI parameters that can be set in the submission of the page. For example, if the skip_header parameter is set, it will just execute the post-event and return, giving the post-event complete control over the response.
RANDOM USEFUL METHODS
$fm->cgi()
Returns the CGI object that FormMagick is using.
$fm->wherenext($pagename);
Set the magic "wherenext" CGI parameter, which tells FormMagick which page to display next. Particularly useful when used in a page’s post-event routine, to (for instance) go to a different next page depending on what the user entered on the last page.
This method is also exported so you can use it in the form itself, for instance:
<page post-event="wherenext(’SomePage’)">
With no args, returns the value of the "wherenext" parameter.
$fm->go_to_finish()
Like wherenext(), except that it says to go to the finish and perform the form post-event and do all the things that would ordinarily be donewhen a user clicks the "Finish" button. Can be used as a method or as an exported function, so you can do things like:
<page post-event="go_to_finish()">
FORMMAGICK XML TUTORIAL
Form descriptions
The main thing you need to know to use FormMagick is the structure and syntax of FormMagick forms. FormMagick is based on a "wizard" sort of interface, in which one form has many pages, and each page has many fields. This is expressed as a nested hierarchy of XML elements.
For examples of FormMagick XML, see the "examples/" directory included in the FormMagick distribution. The XML must comply with the FormMagick DTD (included in the distribution as FormMagick.dtd). A command-line tool to test compliance is planned for a future release.
Here is an explanation of the nesting of elements and the attributes supported by each element.
FORMS
Form sub-elements
A form may contain the following elements:
- page
Form attributes
The following attributes are supported for forms:
- pre-event (a subroutine to run before the form is displayed)
- post-event (a subroutine to run after the form is completed)
Example
<form pre-event="setup()" post-event="submit()> <page> ... </page> <page> ... </page> <page> ... </page> </form>
PAGES
Page sub-elements
A page may contain the following sub-elements:
- description
- field
Page attributes
The following attributes are supported for pages:
- name (required)
- pre-event=<func>
- post-event=<func>
- menu=<func>
Example
<page name="RoomType" menu="show_menu()" post-event="check_availability"> <description> Please provide us with details of your preferred room. </description> <field> ... </field> <field> ... </field> <field> ... </field> </page>
FIELDS
Fields are the most important part of the form definition. Several types of HTML fields are supported, and each one has various attributes associated with it.
Field types
You can specify the type of HTML field to be generated using the type attribute:
<field type="...">
The following field types are supported:
text
A plain text field. You may optionally use the size attribute to modify the size of the field displayed. To restrict the length of data entered by the user, use the maxlength() validation routine.
select
A dropdown list. You must provide the options attribute to specify the contents of the list (see below for the format of this attribute). If you set the multiple attribute to 1, multiple selections will be enabled. The optional size attribute sets the number of items displayed at once.
radio
Radio buttons allow users to choose one item from a group. This field type requires the options attribute (as for select, above).
checkbox
This field type provides a simple check box for yes/no questions. The checked attribute is optional, but if set to 1 will make the checkbox checked by default.
password
The password field type is like a text field, but obscures the data typed in by the user.
file
This field type allows the upload of a file by the user.
textarea
A multi-line text field allowing the input of blocks of text. Defaults to 5 rows and 60 columns, but you can specify "rows" and "cols" arguments to change that.
literal
A field that is just printed literally. Useful if you want to just print out a non-editable bit of text in the same sort of layout as the other fields in the form.
You may specify a subroutine to generate the field type. This is particularly useful in "create or modify" type forms where one or more fields will be input fields when creating or literals when modifying.The subroutine can return any of the above type as a string.
Field sub-elements
The following elements may be nested within a field:
- label (a short description; required)
- description (a more verbose description; optional)
Other field attributes
Fields must ALWAYS have a type (described in the previous section) and an id attribute, which is a unique name for the field. Each type of field may have additional required attributes, and may support other optional attributes.
Here is a list of optional attributes for fields:
value
A default value to fill in; see below for more information on the format of this field.
validation
a list of validation functions; see CGI::FormMagick::Validator for more information on this subject.
options
A list of options required for a select list or radio buttons; see below for more information on the format of this attribute.
checked
For checkbox fields, used to make the box checked by default. Defaults to 0.
multiple
For select fields, used to allow the user to select more than one value.
size
For select fields, height; for text and textarea fields, length.
display
This attribute is a callback to a function that returns true or false. If true, the field is displayed, and validated during form submission. If false, it is not.
Notes on parsing of value attribute
If your value attribute ends in parens, it’ll be taken as a subroutine to run. Otherwise, it’ll just be taken as a literal.
This will be literal:
value="username"
This will run a subroutine:
value="get_username()"
The subroutine will be passed the CGI object as an argument, so you can use the CGI params to help you generate the value you need. Your subroutine should return a string containing the value you want. Notes on parsing of options attribute The options attribute has automagical Do What I Mean (DWIM) abilities. You can give it a value which looks like a Perl list, a Perl hash, or a subroutine name. For instance:
options="’red’, ’green’, ’blue’" options="’ff0000’ => ’red’, ’00ff00’ => ’green’, ’0000ff’ => ’blue’" options="get_colors()"
How it works is that FormMagick looks for the => operator, and if it finds it it evals the options string and assigns the result to a hash. If it finds a comma (but no little => arrows) it figures it’s a list, and evals it and assigns the results to an array. Otherwise, it tries to interpret what’s there as the name of a subroutine in the scope of the script that called FormMagick, expecting to get back a value which is either an arrayref or a hashref, which it will deal with appropriately in either case.
A few gotchas to look out for:
- Make sure you quote strings in lists and hashes. "red,blue,green" will fail (silently) because of the barewords.
- Single-element lists ("red") will fail because the DWIM parsing doesn’t find a comma there and treats it as the name of a subroutine. But then, a single-element radio button group or select dropdown is pretty meaningless anyway, so why would you do that?
- Arrays will result in options being sorted in the same order they were listed. Hashes will be sorted by value using the Perl’s cmp() function (ASCIIbetical sort, in other words).
- An anti-gotcha: subroutine names do not require the parens on them. "get_colors" and "get_colors()" will work the same.
INTERNAL, DEVELOPER-ONLY ROUTINES
The following routines are used internally by FormMagick and are documented here as a developers’ reference. If you are using FormMagick to develop web applications, you can skip this section entirely.
magic_wherenext
We allow FM users to set the "wherenext" param explicitly in their code, to do branching of program logic. This routine checks to see if they have a magic "wherenext" param and returns it. Gives undef if it’s not set.
nopost
Often, you want to provide the ability to navigate to a new page with out validating the last page. When that is the case, you should set the ’nopost’ CGI param, which is checked with this method, and then deleted to prevent is being remembered for the next submission.
prepare_for_next_page
This does all the things needed before going on to the next page. Specifically, it validates the data from this page, and then if validation was successful it puts the current page onto the page stack and then sets page_number to whatever page we should be visiting next.
$fm->cleanup_checkboxes()
Checkbox params only get passed around if they’re checked. An unchecked box doesn’t send "checkbox=0" ... no, it just completely fails to send anything at all. This is a PITA, as it’s impossible to distinguish an explicity unchecked box from one that never got seen at all. This subroutine is intended to clean up the mess, by checking the checkboxes that were expected on the current page against what it actually saw on the CGI parameters, and explicitly setting any missing ones to 0.
$fm->commit_session()
Commits a session’s details to disk, in the same way as CGI::Persistent. Needed by cleanup_checkboxes().
get_option_labels_and_values ($fieldinfo)
returns labels and values for fields that require them, by running a subroutine or whatever else is needed. Returns a hashref containing:
{ labels => \@options_labels, $vals => \@option_values }
parse_options_attribute($options_field)
parses the options attibute from a field element and returns a reference to either a hash or an array containing the relevant data to fill in a select box or a radio group.
do_external_routine($self, $routine, @optional_args)
Runs an external routine, for whatever purpose (filling in default values of fields, validation, etc). If anything is in @optional_args, the routine is called using those. If @optional_args is ommitted, then $self->{cgi} is passed. Returns the return value of the routine, or undef on failure. Also emits a warning (to your webserver’s error log, most likely) if it can’t run the routine.
The routine is always called in the package which called FormMagick (usually main::, but possibly something else).
The CGI object is passed to your routine, so you can do stuff like $cgi->param("foo") to it to find out CGI parameters and so on.
SEE ALSO
CGI::FormMagick::Utils
CGI::FormMagick::Events
CGI::FormMagick::Setup
CGI::FormMagick::L10N
CGI::FormMagick::Validator
CGI::FormMagick::FAQ
BUGS
The validation attribute must be very carefully formatted, with spaces between the names of routines but not between the arguments to a routine. See description above.
AUTHOR
Kirrily "Skud" Robert <skud@infotrope.net>
Contributors:
Shane R. Landrum <slandrum@turing.csc.smith.edu> James Ramirez <jamesr@cogs.susx.ac.uk>
More information about FormMagick may be found at http://sourceforge.net/projects/formmagick/