[Catalyst] "Best Practice" for validating form input

Bill Moseley moseley at hank.org
Mon Aug 1 22:56:18 CEST 2005


On Mon, Aug 01, 2005 at 04:19:14PM -0400, Sean Davis wrote:
> In CGI::App, I typically had a form submit back to itself and them used
> something like ->forward (an "internal redirect") to move to the next page
> if the form validated.  Using URL mapping, one needs to do a real redirect.
> I'm just curious what peoples' thoughts are on an idiom that works for
> Catalyst, as the two-queries per page (one to collect data, and the second
> to do a redirect after the data is validated) seems slightly tedious for
> many cases.

I'm new too all this, too.  Here's what I'm doing in one controller --
I'll post in hopes someone can point out what I could do better.. ;)

This is in a general CRUD controller.


sub update_record : Private {
    my ( $self, $c ) = @_;

    my $form = $c->form(
        optional    => [ qw/ optional / ],
        required    => [ qw/ name foo bar active / ],
        constraints => {
            active => qr/(?:0|1)/,
        },
        missing_optional_valid  => 1,  # see Data::FormValidator
    );

    if ( $form->has_missing || $form->has_invalid ) {
        $c->stash->{message} = 'Fix the form, will ya!';
        $c->stash->{errors} = $form->msgs;
        return $c->forward('edit');
    }

    # "item" was loaded a previous action.

    if ( $c->stash->{item} ) {
        $c->stash->{item}->update_from_form( $c->form );
    } else {
        $c->stash->{class}->create_from_form( $c->form );
    }

    # redisplay the list of items
    $c->forward('list');
}

I'm using Catalyst::Plugin::FormValidator and ::FillInForm which does
a bit of the magic.  Namely, it calls FillInForm automatically when it
seems $form->has_missing or $form->has_invalid.





-- 
Bill Moseley
moseley at hank.org




More information about the Catalyst mailing list