[Catalyst] Form validation in insert() and update()?

Bill Moseley moseley at hank.org
Tue May 15 20:19:01 GMT 2007


On Tue, May 15, 2007 at 11:42:52AM -0700, mla wrote:
> And where do you handle the validation? Only in the controller or in
> both the model and controller?

Controller only in my case.  There could be extra validation in the
ORM, and of course in the database.

> Could you give a short example of taking an actual field from the 
> request parameters, validating it, and updating a row with it?

I don't work on the field level, but the form level.  The form knows
the collection of fields make up the form, and knows how to validate
each field.  It also knows how to update the database.

I do it like this:

    package MyApplication::Controller::User;
    use strict;
    use MyApplication::Form::User;

    sub edit : Local {
        my ( $self, $c, $id ) = @_;

        # Create the form object
        my $form = MyApplication::Form::User->new( $id );


        # Update or create the user record if form posted and form validates
        $form->update_from_from( $c->request->parameters  )
            if $c->form_posted;


        # Pass form object to template so can display fields
        # and any error messages.
        $c->stash->{form} = $form;

    }


Where MyApplication::Form defines the fields and any custom validation
requirements.  That same form module can be used outside of Catalyst.

Actually, since the form is named after the action and the above code
is the often the same for different forms, I have a shortened
version I use under Catalyst:

    sub edit : Local {
        my ( $self, $c, $id ) = @_;

        $c->update_from_form( $id );
    }

Where $c->update_from_form requires the form module and does
everything else the first example does.  I commonly do a redirect
if $c->update_from_form returns true.



-- 
Bill Moseley
moseley at hank.org




More information about the Catalyst mailing list