| ZForm User Manual | ||
|---|---|---|
| <<< Previous | Next >>> | |
Let's add some more fields to our example, which shall henceforth be called example 2.
package Example2;
use base ZForm;
sub setup {
my $self = shift();
# Define the form
my $fields = [
{'rm' => {
'type' => 'hidden',
'attr' => {
'default' => 'display_data'}}},
{'title' => {
'type' => 'popup_menu',
'label' => 'Title',
'attr' => {
'values' => ['Mr', 'Mrs', 'Ms', 'Dr'],
}}},
{'name' => {
'type' => 'textfield',
'label' => 'Your name',
'attr' => {
'size' => '30'}}},
{'descr' => {
'type' => 'textfield',
'label' => 'Description',
'required' => 'no',
'attr' => {
'size' => '30'}}},
{'evilspam' => {
'type' => 'checkbox',
'label' => 'spam is evil',
'required' => 'no',
'attr' => {}}},
{'checkbox_group' => {
'type' => 'scrolling_list',
'label' => 'Choose some',
'attr' => {
values => ['eenie','meenie','minie','moe'],
defaults => ['eenie','minie'],
multiple => 'true'}}},
];
$self->form_def($fields);
}
1; |
And the application logic, example2.cgi:
#!/usr/bin/perl
use lib '.';
use strict;
use warnings;
use CGI;
use Example2;
# Create a new cgi object
my $q = new CGI;
# Create an instance of our form and attach the cgi object
my $f = new Example2(cgi => $q);
# Placeholder for output
my $output = '';
my $title;
my $descr;
if(defined($q->param('rm')) &&
$q->param('rm') eq 'display_data') {
# User clicked submit, so validate the form
if($f->validate()) {
# It validated! Display the data
$output = $f->display_data_only();
} else {
# Didn't validate, so display the form with errors
$output = $f->display();
}
} else {
# The user has not yet clicked submit, so display the empty form
$output = $f->display();
}
# Display the output
print($q->header, $output); |
Notice how the subroutine to display the data has been replaced with $f->display_data_only().
Now try it out! Notice that if you leave the name field blank and choose a title, the chosen title persists. This makes persistence for popup menus, checkboxes, list boxes and radio groups easy for you!
Now, let's be nefarious. In the URL bar, append the following:
?title=hack-a-thon&rm=display_data |
Notice the "invalid value" next to the drop down menu? This makes it harder to subvert your form. Most applications don't check to be sure that the popup menus and scrolling lists have valid values.
| <<< Previous | Home | Next >>> |
| Hello World Example | Generating and Using Templates |