]> git.decadent.org.uk Git - maypole.git/blob - lib/Apache/MVC/Model/CDBI.pm
Swathes of documentation.
[maypole.git] / lib / Apache / MVC / Model / CDBI.pm
1 package Apache::MVC::Model::CDBI;
2 use base qw(Apache::MVC::Model::Base Class::DBI);
3 use Lingua::EN::Inflect::Number qw(to_PL);
4 use Class::DBI::AsForm;
5 use Class::DBI::FromCGI;
6 use Class::DBI::AbstractSearch;
7 use CGI::Untaint;
8 use strict;
9
10 sub related {
11     my ($self, $r) = @_;
12     # Has-many methods; XXX this is a hack
13     map {to_PL($_)} 
14     grep { exists $r->{config}{ok_tables}{$_} }
15     map {$_->table}
16     keys %{shift->__hasa_list || {}}
17 }
18
19 sub do_edit :Exported {
20     my ($self, $r) = @_;
21     my $h = CGI::Untaint->new(%{$r->{params}});
22     my ($obj) = @{$r->objects};
23     if ($obj) {
24         # We have something to edit
25         $obj->update_from_cgi($h);
26         warn "Updating an object ($obj) with ".Dumper($h); use Data::Dumper;
27     } else {
28         $obj = $self->create_from_cgi($h);
29     }
30     if (my %errors = $obj->cgi_update_errors) {
31         # Set it up as it was:
32         warn "There were errors: ".Dumper(\%errors)."\n";
33         $r->{template_args}{cgi_params} = $r->{params};
34         $r->{template_args}{errors} = \%errors;
35         $r->{template} = "edit";
36     } else {
37         $r->{template} = "view";
38     }
39     $r->objects([ $obj ]);
40 }
41
42 sub delete :Exported {
43     my ($self, $r) = @_;
44     $_->SUPER::delete for @{ $r->objects };
45     $r->objects([ $self->retrieve_all ]);
46     $r->{template} = "list";
47 }
48
49 sub adopt {
50     my ($self, $child) = @_;
51     $child->autoupdate(1);
52     $child->columns( Stringify => qw/ name / );
53 }
54
55 sub search :Exported {
56     return shift->SUPER::search(@_) if caller eq "Class::DBI"; # oops
57     my ($self, $r) = @_;
58     my %fields = map {$_ => 1 } $self->columns;
59     my $oper = "like"; # For now
60     use Carp; Carp::confess("Urgh") unless ref $r;
61     my %params = %{$r->{params}};
62     my %values = map { $_ => {$oper, $oper eq "like" ? "%".$params{$_}."%" 
63                                                      :$params{$_} } }
64                  grep { $params{$_} and $fields{$_} } keys %params;
65
66     $r->objects([ %values ? $self->search_where(%values) : $self->retrieve_all ]);
67     $r->template("list");
68     $r->{template_args}{search} = 1;
69 }
70
71 1;
72
73 =head1 NAME
74
75 Apache::MVC::Model::CDBI - Model class based on Class::DBI
76
77 =head1 DESCRIPTION
78
79 This is a master model class which uses C<Class::DBI> to do all the hard
80 work of fetching rows and representing them as objects; instead, it
81 concentrates on the actions that can be performed in the URL:
82 C<do_edit>, C<delete> and C<search>.