| ZForm User Manual | ||
|---|---|---|
| <<< Previous | Next >>> | |
Often times, you will want to place a set of default values into a form. I know that I do this when editing a record in a database.
Default values for a form can be set with the ZForm->values() method. This method can also be used to retreive the values of a form as well, which is covered in the next section.
The list of values can be set using a reference to a hash. Let's jump in with an example and modify our point of contact example:
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 = '';
# Define some default values
my $default_vals = {
'rm' => 'validate',
'fname' => 'Coach',
'lname' => 'Z',
'phone' => [
{'number' => '555-5551',
'type' => '0'},
{'number' => '555-5552',
'type' => '3'},
{'number' => '555-5553',
'type' => '2'},
{'number' => '555-5554',
'type' => '1'},
]
};
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
$f->values($default_vals);
$output = $f->display();
}
# Display the output
print($q->header, $output); |
The format of the hash is field_name1 => value1, ... field_nameN => valueN. When defining the default values for a form fragment, place a reference to a hash into an array. Even if the form fragment is only repeated once.
| <<< Previous | Home | Next >>> |
| Form Fragments | Retrieving Form Input |