+use base qw(Maypole::Model::Base Class::DBI);
+use Maypole::Model::CDBI::AsForm;
+use CGI::Untaint::Maypole;
+
+use Class::DBI::FromCGI;
+use Class::DBI::Loader;
+use Class::DBI::AbstractSearch;
+use Class::DBI::Plugin::RetrieveAll;
+use Class::DBI::Pager;
+
+use Lingua::EN::Inflect::Number qw(to_PL);
+use attributes ();
+
+###############################################################################
+# Helper methods
+
+=head1 Action Methods
+
+Action methods are methods that are accessed through web (or other public) interface.
+
+=item do_edit
+
+If there is an object in C<$r-E<gt>objects>, then it should be edited
+with the parameters in C<$r-E<gt>params>; otherwise, a new object should
+be created with those parameters, and put back into C<$r-E<gt>objects>.
+The template should be changed to C<view>, or C<edit> if there were any
+errors. A hash of errors will be passed to the template.
+
+=cut
+
+sub do_edit : Exported {
+ my ($self, $r, $obj) = @_;
+
+ my $config = $r->config;
+ my $table = $r->table;
+
+ # handle cancel button hits
+ if ( $r->{params}->{cancel} ) {
+ $r->template("list");
+ $r->objects( [$self->retrieve_all] );
+ return;
+ }
+
+ my $required_cols = $config->{$table}->{required_cols} || [];
+ my $ignored_cols = $r->{config}{ $r->{table} }{ignore_cols} || [];
+
+ ($obj, my $fatal, my $creating) = $self->_do_update_or_create($r, $obj, $required_cols, $ignored_cols);
+
+ # handle errors, if none, proceed to view the newly created/updated object
+ my %errors = $fatal ? (FATAL => $fatal) : $obj->cgi_update_errors;
+
+ if (%errors) {
+ # Set it up as it was:
+ $r->template_args->{cgi_params} = $r->params;
+ $r->template_args->{errors} = \%errors;
+
+ undef $obj if $creating;
+ $r->template("edit");
+ } else {
+ $r->template("view");
+ }
+
+ $r->objects( $obj ? [$obj] : []);
+}
+
+# split out from do_edit to be reported by Mp::P::Trace
+sub _do_update_or_create {
+ my ($self, $r, $obj, $required_cols, $ignored_cols) = @_;
+
+ my $fatal;
+ my $creating = 0;
+ my $h = CGI::Untaint::Maypole->new( %{$r->params} );
+
+ # update or create
+ if ($obj) {
+ # We have something to edit
+ eval { $obj->update_from_cgi( $h => {
+ required => $required_cols,
+ ignore => $ignored_cols,
+ } ) };
+ $fatal = $@;
+ } else {
+ eval {
+ $obj = $self->create_from_cgi( $h => {
+ required => $required_cols,
+ ignore => $ignored_cols,
+ } )
+ };
+
+ if ($fatal = $@) {
+ warn "$fatal" if $r->debug;