package CGI::Form::Table;
use strict;
use warnings;
=head1 NAME
CGI::Form::Table - create a table of form inputs
=head1 VERSION
version 0.161
$Id: /my/cs/projects/formtable/trunk/lib/CGI/Form/Table.pm 27835 2006-11-11T04:18:20.685136Z rjbs $
=cut
our $VERSION = '0.161';
=head1 SYNOPSIS
use CGI::Form::Table;
my $form = CGI::Form::Table->new(
prefix => 'employee',
columns => [qw(lname fname job age)]
);
print $form->as_html;
print $form->javascript;
=head1 DESCRIPTION
This module simplifies the creation of an HTML table containing form inputs.
The table can be extended to include extra rows, and these rows can be removed.
Each has a unique name, and on form submission the inputs are effectively
serialized.
L will use the CGI module to produce a data structure
based on the parameters submitted by a form of this type.
=head1 METHODS
=head2 C<< CGI::Form::Table->new(%arg) >>
This method constructs a new form. The only required arguments are
C, which names the columns that will be in the form table, and
C, which gives the unique prefix for input fields.
If given, C specifies how many rows should initially be in the
form.
Instead of C, you can pass C, a reference to an
array of hashes providing values for the columns of each row. For example:
my $table = CGI::Form::Table->new(
prefix => "charsheet",
columns => [ qw(ability score) ],
initial_values => [
{ ability => 'Str', score => '18/00' },
{ ability => 'Cha', score => '11' }
]
);
C, if passed, is a hash of text strings to use as column
headers. The keys are column names. Columns without C entries
are headed by their names.
Another argument, C, may be passed. It must contain a hashref,
with entries providing subs to produce initial content. The subs are passed the
form object, the row number, and the name of the column. For example, to add a
reminder of the current row in the middle of each row, you might create a form
like this:
my $form = CGI::Form::Table->new(
prefix => 'simpleform',
columns => [qw(one two reminder three four)],
column_content => {
reminder => sub { $_[1] }
}
);
This can be useful for forms that require SELECT elements or other complicated
parts. (The JavaScript will just copy the column value when new rows are added,
updating the name attribute.)
=cut
sub new {
my ($class, %arg) = @_;
return unless $arg{columns};
return unless $arg{prefix};
$arg{initial_rows} = 1 unless $arg{initial_rows};
$arg{initial_rows} = @{$arg{initial_values}}
if ($arg{initial_values} && @{$arg{initial_values}} > $arg{initial_rows});
bless \%arg => $class;
}
=head2 C<< $form->as_html >>
This returns HTML representing the form object. JavaScript is required to make
the form expandible/shrinkable; see the C method. (L"SEE ALSO">)
=cut
sub as_html {
my ($self) = @_;
my $prefix = $self->{prefix};
my $column_headers = join q{},
map { "\t\t\t