PageRenderTime 29ms CodeModel.GetById 24ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/HTML/FormHandler/Field/Duration.pm

http://github.com/gshank/html-formhandler
Perl | 57 lines | 39 code | 16 blank | 2 comment | 1 complexity | 7a4dce6b146532d97f7229b65c7943aa MD5 | raw file
 1package HTML::FormHandler::Field::Duration;
 2# ABSTRACT: DateTime::Duration from HTML form values
 3
 4use Moose;
 5extends 'HTML::FormHandler::Field::Compound';
 6use DateTime;
 7
 8=head1 SubFields
 9
10Subfield names:
11
12  years, months, weeks, days, hours, minutes, seconds, nanoseconds
13
14For example:
15
16   has_field 'duration'         => ( type => 'Duration' );
17   has_field 'duration.hours'   => ( type => 'Hour' );
18   has_field 'duration.minutes' => ( type => 'Minute' );
19
20Customize error message 'duration_invalid' (default 'Invalid value for [_1]: [_2]')
21
22=cut
23
24our $class_messages = {
25    'duration_invalid' => 'Invalid value for [_1]: [_2]',
26};
27
28sub get_class_messages  {
29    my $self = shift;
30    return {
31        %{ $self->next::method },
32        %$class_messages,
33    }
34}
35
36
37sub validate {
38    my ($self) = @_;
39
40    my @dur_parms;
41    foreach my $child ( $self->all_fields ) {
42        unless ( $child->has_value && $child->value =~ /^\d+$/ ) {
43            $self->add_error( $self->get_message('duration_invalid'), $self->loc_label, $child->loc_label );
44            next;
45        }
46        push @dur_parms, ( $child->accessor => $child->value );
47    }
48
49    # set the value
50    my $duration = DateTime::Duration->new(@dur_parms);
51    $self->_set_value($duration);
52}
53
54__PACKAGE__->meta->make_immutable;
55use namespace::autoclean;
561;
57