PageRenderTime 25ms CodeModel.GetById 12ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/HTML/FormHandler/Render/Table.pm

http://github.com/gshank/html-formhandler
Perl | 86 lines | 66 code | 19 blank | 1 comment | 5 complexity | 011a4e774d2fe85acb0fe51425eebc2e MD5 | raw file
 1package HTML::FormHandler::Render::Table;
 2# ABSTRACT: render a form with a table layout
 3
 4use Moose::Role;
 5
 6with 'HTML::FormHandler::Render::Simple' =>
 7    { -excludes => [ 'render', 'wrap_field', 'render_end', 'render_start' ] };
 8use HTML::FormHandler::Render::Util ('process_attrs');
 9
10=head1 SYNOPSIS
11
12Include this role in a form:
13
14   package MyApp::Form::User;
15   use Moose;
16   with 'HTML::FormHandler::Render::Table';
17
18Use in a template:
19
20   [% form.render %]
21
22=cut
23
24sub render {
25    my $self = shift;
26
27    my $output = $self->render_start;
28    $output .= $self->render_form_errors;
29    foreach my $field ( $self->sorted_fields ) {
30        $output .= $self->render_field($field);
31    }
32    $output .= $self->render_end;
33    return $output;
34}
35
36sub render_start {
37    my $self   = shift;
38
39    my $attrs = process_attrs($self->attributes);
40    return qq{<form$attrs><table>};
41}
42
43sub render_form_errors {
44    my $self = shift;
45
46    return '' unless $self->has_form_errors;
47    my $output = "\n<tr class=\"form_errors\"><td colspan=\"2\">";
48    $output .= qq{\n<span class="error_message">$_</span>}
49        for $self->all_form_errors;
50    $output .= "\n</td></tr>";
51    return $output;
52}
53
54sub render_end {
55    my $self = shift;
56    my $output .= "</table>\n";
57    $output .= "</form>\n";
58    return $output;
59}
60
61sub wrap_field {
62    my ( $self, $field, $rendered_field ) = @_;
63
64    my $attrs = process_attrs($field->wrapper_attributes);
65    my $output = qq{\n<tr$attrs>};
66    my $l_type = $field->widget eq 'Compound' ? 'legend' : 'label';
67    if ( $l_type eq 'label' ) {
68        $output .= '<td>' . $self->render_label($field) . '</td>';
69    }
70    elsif ( $l_type eq 'legend' ) {
71        $output .= '<td>' . $self->render_label($field) . '</td></tr>';
72    }
73    if ( $l_type ne 'legend' ) {
74        $output .= '<td>';
75    }
76    $output .= $rendered_field;
77    $output .= qq{\n<span class="error_message">$_</span>} for $field->all_errors;
78    if ( $l_type ne 'legend' ) {
79        $output .= "</td></tr>\n";
80    }
81    return $output;
82}
83
84use namespace::autoclean;
851;
86