[Catalyst] CDBI => Web (opposite of Class::DBI::FromForm)
Bill Moseley
moseley at hank.org
Mon Nov 7 04:49:54 CET 2005
On Mon, Nov 07, 2005 at 02:47:07AM +0100, Roland Moriz wrote:
> I think this is not DRY and can be done by ::FillInForm object filled
> with a retrieved CDBI object - just the inverse way that
> Class::DBI::FromForm goes from a ::FormValidator object...
>
> Should be possible, shouldn't it?
> Do we have such a functionality already available?
I'd recommend looking at Rose-HTML-Form. I wrote a subclass for it so
I can use FormValidator-like profiles for input and also so
select/radio options are automatically loaded from the database based
on has_a (or has_many for many-to-many) relationships. Rose-HTML-Form
can also generate html widgets which makes generating the forms quite
easy.
I like Rose-HTML-Form so much that one night after a few drinks I
foolishly decided to write my own form processing code based mostly on
Rose-HTML-Form's design, mixed in with what I like from FormValidator.
It's not ready for public consumption yet until I get time to package
and write a few tests. Plus, I'm not so sure I won't go back to using
Rose-HTML-Form again.
Anyway, here's how it works:
SYNOPSIS
In an application you might want a controller to handle creating and
updating a "User" record. And not want to write much code. Here's using
Catalyst as an example:
package MyApplication::C::User;
use strict;
use MyApplication::Form::User;
sub edit : Local {
my ( $self, $c, $id ) = @_;
my $form = MyApplication::Form::User->new( $id );
$form->update_from_from( $c->request->parameters )
if $c->request->parameters->{update};
$c->stash->{template} = 'user.tt';
$c->stash->{form} = $form;
}
The form class might then look like this:
package MyApplication::Form::User;
use strict;
use base 'Form::Model::CDBI';
sub object_class { 'DB::User' }
sub profile {
my $self = shift;
return {
required => {
name => 'Text',
age => 'PosInteger',
sex => 'Select',
birthdate => 'DateTimeDMYHM',
},
optional => {
hobbies => 'Multiple',
address => 'Text',
city => 'Text',
state => 'Select',
},
dependency => [
[qw/ address city state /],
],
};
}
sub options_sex {
return (
m => 'Male',
f => 'Female',
);
}
sub validate_age {
my ( $self, $field ) = @_;
$field->add_error('Sorry, you must be 18')
if $field->value < 18;
}
1;
--
Bill Moseley
moseley at hank.org
More information about the Catalyst
mailing list