| ZForm User Manual | ||
|---|---|---|
| <<< Previous | Next >>> | |
Form fragments are a way of defining a small piece of a form that can be used within other forms. This allows one to define a single way of displaying, validating and gathering a piece of data.
As usual, we'll get right to an example that describes getting a first name, last name, and up to five phone numbers:
Phone.pm:
Package Phone;
use base ZForm;
sub setup {
my $self = shift();
my $fields = [
{'number' => {
'type' => 'textfield',
'label' => 'Phone Number',
'attr' => {
'size' => '30'}}},
{'type' => {
'type' => 'popup_menu',
'label' => 'Phone Type',
'attr' => {
'values' => ['0', '1', '2', '3'],
'labels' => {'0' => 'Home',
'1' => 'Office',
'2' => 'Cell',
'3' => 'Pager'}
}}},
];
$self->form_def($fields);
}
1; |
POC.pm:
package POC;
use Phone;
use base ZForm;
sub setup {
my $self = shift();
my $fields = [
{'rm' => {
'type' => 'hidden',
'attr' => {
'default' => 'validate'}}},
{'fname' => {
'type' => 'textfield',
'label' => 'First Name',
'attr' => {
'size' => '30'}}},
{'lname' => {
'type' => 'textfield',
'label' => 'Last Name',
'attr' => {
'size' => '30'}}},
{'phone' => {
'type' => 'form',
'repeat' => '4',
'form' => new Phone}},
];
$self->form_def($fields);
}
1; |
poc.cgi
#!/usr/bin/perl
use lib '.';
use strict;
use warnings;
use CGI;
use CGI::Carp;
use POC;
# Create a new cgi object
my $q = new CGI;
# Create an instance of our form and attach the cgi object
my $f = new POC(cgi => $q);
# Placeholder for output
my $output = '';
if(defined($q->param('rm')) && $q->param('rm') eq 'validate') {
# 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); |
The magic portion is in POC.pm:
{'phone' => {
'type' => 'form',
'repeat' => '4',
'form' => new Phone}}, |
This states that the field type is a form, repeat it 4 times. The form attribute is a reference to a ZForm object.
| <<< Previous | Home | Next >>> |
| Validation | Setting Default Values |