![]() |
![]() |
||||||
|
|||||||
POD documentation > HTML formatting > FormBuilder.pm posted on 3:10 PM, July 12, 2009
FormBuilderThis is a simple utility for building forms. It is content-agnostic, so it can easily be adapted to various web applications. It is used by higher-level form construction methods in ExSite, which handle all of the ExSite-specific logic.
UsageA typical usage is shown below.
my $f = new ExSite::FormBuilder(method=>"post",action=>"/cgi-bin/foo.cgi"); In addition to new() parameters:
$f->method($get_or_post); $f->template($all_in_one_template); $f->input(%first_input); The allowed options are described below, under Input Parameters. Note that you can also use the following methods for textarea and select inputs: $f->textarea(%options); These work similarly to print $f->make(); $f->init(); In practice, these steps can be done in any order. Templates will
override any previously-specified templates, but are not actually used
until More advanced usage may involve installation of custom validation scripts, and more sophisticated use of the input generation functions. Details are given below.
Input ParametersInput parameters are passed to the
Input tag attributes
Input field flagsThe following parameters accept true/false values:
Other modifiersThe following parameters are also accepted, although they are not input attributes:
Note that each input is generated as a new form field, unless it is a radio input of the same name as a previous input; in that case, the radio button is appended to the other radio buttons of that name.
Form PresetsYou can pass individual field values in to each call to $f->values(%data);
ValidationFormBuilder allows for client-side validation of forms. If you specify the ``required'' parameter for any inputs in your form, then special validation javascript will be built in to ensure that these fields contain data before the form will submit. We only check that data is present; we do not check that it conforms to any particular pattern. To do pattern checks, use a custom validation routine (see below). Validation is automatic; you need not do anything other than include
the ``required'' parameter in your This is a convenience for the end-user, to prevent unnecessary submissions and annoying waits in case of an incorrectly-filled form. It can be circumvented, so it does not replace server-side validation, and should never be considered a security measure. Validation requires that the required form elements and the form itself have unique IDs. FormBuilder will assign unique IDs to these elements if you have not specified any yourself. If you specify your own IDs, FormBuilder will try to use those instead. However, it does not validate that the ID you have specified is unique in the form or the document, so take care when specifying your own IDs. Failed validation will result in a Javascript alert indicating which fields are missing. To require a user to accept some terms before the form will submit, simply add a checkbox input that is required, eg. $f->input(name=>"termsOfService", (Remember that this is not a bulletproof method for ensuring the form does not get submitted without the box checked.) Warning for radio buttons: radio buttons consist of multiple input tags that are grouped under a single name. If you set a single radio button as required, that means you must select that one button, and any other button choices will not be accepted. This is probably not what you want. Similarly if you make all but one required, then you will not be able to select that one button. To get the behaviour that at least one button in the whole group must be selected, and any button in the group may be selected, then each button in the group must be set as required.
Custom ValidationIf you want to inject your own validation javascript into the form, do this: $f->validate($my_js_call,$my_js_script); where Your validation script must return You can define any number of custom validation scripts, and they will all be executed, joined by the '&&' operator. Each script can be treated as one validation pass; the last pass does generic automatic validation (testing that form fields contain data). All passes must return true for the form to be submitted, and if any return false, the remaining passes will not execute. The auto-generated validation script (described above) is run last in this sequence. This allows custom scripts to manipulate form data before final submission.
ExampleSay we want to not only test a field to make sure that data has been provided, but also test that it matches an allowed pattern of values. We can set the field as required, to make sure that data is present: $f->input(name=>"email",required=>1); Then we can add a custom validator:
$f->validate("validate_email(this)",
"function validate_email(f) {
var re = new RegExp('.+@.+\\.com'); // not a very good regexp
if (f.email.value.match(re)) {
return true;
}
alert('Invalid email address!');
return false;
}");
The first pass of validation checks that the email field (among
others) contains data. If all required fields contain data, then
Styling Required FieldsRequired files will be wrapped in some CSS markup to allow you to highlight them in some way. If you want the required field highlighting, but do not want
client-side validation (ie. you will handle it server-side), then pass
a negative non-zero value (eg.-1) for the You can also optionally insert additional text/html before or after
the prompt on required fields. Use the object attributes
$f->set("required_suffix","*"); # append a star to required fields
Custom InputsYou can manually specify the input field tag using the If your custom input is complex (for example, multiple input fields,
javascript-driven input controls, etc.), then the built-in validation
may not work. Built-in validation checks for non-null value in the
form element (ie.
Example (date selector)Say we want a date selector with separate selectors for day, month,
and year. We can call the internal my $date_selector = $date_selector now contains the HTML for selecting a date using this aggregate input. Now we want to add this to our form as a ``single'' input field: $f->input(prompt=>"date",input=>$date_selector); If this field is required, we cannot simply set
required=>-1 to mark the field as required, but let
the validation happen on the server
required=>1.
Form TemplatesTemplates allow you some control over how forms are laid out in HTML. There are two styles of template: row-by-row (default), and all-in-one.
Default TemplateBy default, forms are built using row-by-row templates, ie. by concatenating form fields that are each templated using following HTML:
There are enough CSS hooks in this default template to permit a range of styling to be applied to the forms.
Custom TemplatesYou can replace the default row-by-row template with your own using this call: $f->template($top_of_form, $row_by_row_template, $bottom_of_form);
Example $f->template("",
All-in-one TemplatesFor more precise control over layout, you can provide an all-in-one template that specifies where each named input field should go. $f->template($all_in_one_template);
Your all-in-one template should include any required CSS classes in the template HTML, as no further HTML insertions are performed. If you add inputs to your form that are not referenced in the all-in-one template, then FormBuilder will append them to the end of the form using the row-by-row templating method. You can actually specify templates for both methods in this case, by specifying your row-by-row template first, and your all-in-one template second. The last method takes precedence, but the prior method is still saved in case you have untemplated inputs in your form.
Example# row-by-row fallback template for unexpected inputs # all-in-one template for expected inputs
Preformatted RowsSometimes you need to break with the row--by-row template, and add
some custom HTML (whether an input field or not) onto your form. You
can append the special HTML, using an input type of ``preformatted''.
You can use this trick to insert arbitary HTML text into the middle of your forms, such as help text or section headings: $f->input(type=>"preformatted", This example inserts a heading and paragraph into the form, exactly as given. If you provide both a prompt and input, both will be inserted verbatim into the form. If you only include one or the other, only that one will be included. Try to ensure that your concatenated prompt and input fields will fit into the form HTML. For example, if your form template is a table, and your row-by-row template is a row in this table, then your preformatted input should also be a table row that fits into this HTML. For example: $f->input(type=>"preformatted", In this example, note that we did not bother to specify an input. We
also included a template placeholder for Preformatted rows cannot make use of other FormBuilder features such as validation.
Header and Footer HTMLYou can also insert arbitrary HTML before and after the form, using: $f->set("head",$header_html);
These HTML snippets will go outside the form tags.
CSSThe default template makes use of the following CSS classes:
Additionally, required fields may also use the following CSS classes:
Alternating Row StylesSet alternate-row highlighting on as follows: $f->set("highlight_rows",1);
When using row-by-row templating, this will give each row of the form an alternating CSS class of ``A'' or ``B''. These can be used to give each row an alternating background color, as is commonly done for reports. This only works for row-by-row templates (including the default template). If defining a custom row-by-row template, use the tag $f->template("",
To ignore the row class entirely, simply do not reference it in your template.
Custom CSSYou can also specify custom CSS classes when building forms. The
You can also specify arbitrary CSS classes in your templates, instead of using the default classes described above.
FormBuilder and FormThe
ExampleCreate a new $db = new ExSite::Form; Add a database field to this form (ie. a field that maps to a particular database column): $db->input_column(table=>"my_table", Add a field to this form that collects data for a special ExSite datatype: $db->input_exsite(datatype=>"datetime", Add a basic HTML input element that is required: $db->input_html(type=>"text",name=>"email",required=>1); Or (equivalent to previous, going direct to
$f->input(type=>"text",name=>"email",required=>1);
Generate the form: my $form_html = $f->make(); |
Recent ArticlesDocumentation Topicsbest practices (5)
content management (12)
data handling (7)
fundamentals (3)
google (5)
graphic design (21)
html formatting (7)
IT (8)
plug-in modules (28)
POD (32)
programming (48)
RSS (3)
security (3)
SEO (3)
visual tutorial (29)
web protocols (9)
|