[Catalyst] best practices for handling forms?

E R pc88mxer at gmail.com
Mon Sep 20 21:48:31 GMT 2010


Hi,

I am curious what everyone thinks as being the best practices for
handling forms in Catalyst. Are there any Catalyst applications you
have run across which are good examples of how to use Catalyst's
features to handle forms?

To illustrate what I am getting at, below is typical Rails (v2)
controller code which implements updating the attributes of an object:

   def edit
      @book = Book.find(params[:id])
      @subjects = Subject.find(:all)
   end
   def update
      @book = Book.find(params[:id])
      if @book.update_attributes(params[:book])
         flash[:notice] = 'Book successfully updated.'
         redirect_to :action => 'show', :id => @book
      else
         @subjects = Subject.find(:all)
         render :action => 'edit'
      end
   end

In Catalyst, this would be appear something like (and please correct
me if I have made any errors here):

sub edit  :Args(1) {
  my ($self, $c, $id) = @_;
  ... set up $c->stash for template 'edit' ...
  # no need to set $c->stash->{template} - will be set from the current action
}

sub update :Args(1) {
  my ($self, $c, $id) = @_;
  ...process form...
  if (form is valid) {
    ...perform updates...
    $c->flash->{notice} = 'Book successfully updated.';
    $c->res->redirect('show', $id);
  } else {
    ... set up $c->stash for 'edit' template ...
    $c->stash->{template} = 'edit';
  }
}

Any comments on this architecture? Is there a better way? My main problems are:

1. The code ... set up $c->stash for 'edit' template ... is duplicated
in both edit and update (which is also true for the Rails code).

2. Having the template name defaulted from the current action is nice,
but that means we have to explicitly set it in the update method. Is
it better to always explicitly set the template name in a controller
method? Then update could perform a $c->detach('edit', $id) or would
you use $c->go('edit', $id)?

Thanks,
ER



More information about the Catalyst mailing list