http://www.perlmonks.org?node_id=722463


in reply to Life, Love and CGI::Application::Plugin::ValidateRM (and Friends)

Lots of questions here!

First off, remember that HTTP is a stateless protocol, which means that the server(s) do not share any data between requests. You need to do that explicitly, either by putting data in the url, or in a form, or in a session.

Sharing state between requests

You have essentially three options:
  1. Using url parameters: myapp?rm=edit;user=1 produces a page, and adds user=1 to the relevant urls. E.g. myapp?rm=save;user=1. The next request finds the user id with $self->query->param('user').
  2. Using form fields: The same request produces a form with a hidden field:
    <form action="myapp"> <input type="hidden" name="rm" value="save"> <input type="hidden" name="user" value="1">
    The next request finds the user id with $self->query->param('user') as well.
  3. using a session: The same request creates a session, stores user=>1 in it, and sends a cookie with the session id in it along with the output. The next request looks in the session for the "user" parameter.

How to use sessions with CGI::Application

Save yourself headaches, and install CGI::Application::Plugin::Session. Configuration is pretty straightforward. Usage is dead simple too:
sub edit { my $self = shift; my $user_id = $self->query->param( 'user' ); $self->session->param( user => $user_id ); # store it ... } sub save { my $self = shift; my $user_id = $self->session->param( 'user' ); # retrieve it ... }

Form validation strategy

It's handy to have form display and form processing in separate methods. The general pattern of form processing is
  1. Gather input
  2. Validate input
    • If invalid, display the form again with error messages
    • If valid, process the input
Something like this:
sub display_form { ... } sub process_form { my $self = shift; my @input = data_from_query_or_session(); # use CAP::ValidateRM here my @errors = validate( $profile, @input ); if( @errors ) { # HTML::FillInForm makes this easier return $self->display_form( @errors ); } # submission was ok, process the data ... }
Hope that helps :)