package Error;
use HTML::Template;
use strict;
sub new {
my ($class,$file) = @_;
my $self = {
ERRORS => undef, # this key is a list of hashes
file => $file,
};
bless $self, $class;
return $self;
}
sub add_error {
my ($self,$field,$reason) = @_;
push @{$self->{ERRORS}}, {
FIELD => $field,
REASON => $reason,
};
}
sub generate_errors {
my ($self,$file) = @_;
return unless ¬_empty;
my $template = HTML::Template->new(filename => $self->{file});
$template->param(
IS_SINGULAR => (scalar @{$self->{ERRORS}} == 1),
ERRORS => $self->{ERRORS},
);
@{$self->{ERRORS}} = ();
return $template->output;
}
sub not_empty {
my $self = shift;
return ($self->{ERRORS}) ? (scalar @{$self->{ERRORS}} > 0) : 0;
}
1;
####
use Errors;
my $ERROR = Error->new('error.tmpl');
# etc. . . .
sub validate_offer_name {
my $offer_name = strip_spaces($CGI->param('offer_name'));
unless ($offer_name =~ m/^[A-Za-z]\w*$/) {
# ERROR - user entered invalid offer name
$ERROR->add_error('Create New Offer', 'Invalid characters were found');
go_home();
return;
}
if (&check_existing($DBH,$offer_name)) {
# ERROR - name already exists
$ERROR->add_error('Create New Offer', 'That name exists, try again');
go_home();
return;
}
# success - valid name that does not exist
print_create_offer_form($offer_name);
}
sub go_home {
# if there are no errors, $errors will be undefined
my $errors = $ERROR->generate_errors;
my $template = HTML::Template->new(filename => 'home.tmpl');
$template->param(
EXISTING_OFFERS => fetch_all_offers($DBH),
EXISTING_TRANSPORTS => fetch_all_transports($DBH),
ERRORS => $errors,
);
print $CGI->header;
print $template->output;
}
####
The following
error was
errors were
found:
Please try again