751987f7a88cd796449038e087e692015c68dbf5
[freeside.git] / httemplate / edit / process / generic.cgi
1 <%
2
3 # Welcome to generic.cgi.
4
5 # This script provides a generic edit/process/ backend for simple table 
6 # editing.  All it knows how to do is take the values entered into 
7 # the script and insert them into the table specified by $cgi->param('table').
8 # If there's an existing record with the same primary key, it will be 
9 # replaced.  (Deletion will be added in the future.)
10
11 # Special cgi params for this script:
12 # table: the name of the table to be edited.  The script will die horribly 
13 #        if it can't find the table.
14 # redirect_ok: URL to be displayed after a successful edit.  The value of 
15 #              the record's primary key will be passed as a keyword.
16 #              Defaults to (freeside root)/view/$table.cgi.
17 # redirect_error: URL to be displayed if there's an error.  The original 
18 #                 query string, plus the error message, will be passed.
19 #                 Defaults to $cgi->referer() (i.e. go back where you 
20 #                 came from).
21
22
23 use FS::Record qw(qsearchs dbdef);
24 use DBIx::DBSchema;
25 use DBIx::DBSchema::Table;
26
27
28 my $error;
29 my $p2 = popurl(2);
30 my $table = $cgi->param('table');
31 my $dbdef = dbdef or die "Cannot fetch dbdef!";
32
33 my $dbdef_table = $dbdef->table($table) or die "Cannot fetch schema for $table";
34
35 my $pkey = $dbdef_table->primary_key or die "Cannot fetch pkey for $table";
36 my $pkey_val = $cgi->param($pkey);
37
38
39 #warn "new FS::Record ( $table, (hashref) )";
40 my $new = FS::Record::new ( "FS::$table", {
41     map { $_, scalar($cgi->param($_)) } fields($table) 
42 } );
43
44 #warn 'created $new of class '.ref($new);
45
46 if($pkey_val and (my $old = qsearchs($table, { $pkey, $pkey_val} ))) {
47   # edit
48   $error = $new->replace($old);
49 } else {
50   #add
51   $error = $new->insert;
52   $pkey_val = $new->getfield($pkey);
53   # New records usually don't have their primary keys set until after 
54   # they've been checked/inserted, so grab the new $pkey_val so we can 
55   # redirect to it.
56 }
57
58 my $redirect_ok = (($cgi->param('redirect_ok')) ?
59                     $cgi->param('redirect_ok') : $p2."view/$table.cgi");
60 my $redirect_error = (($cgi->param('redirect_error')) ?
61                        $cgi->param('redirect_error') : $cgi->referer());
62
63 if($error) {
64   $cgi->param('error', $error);
65   print $cgi->redirect($redirect_error . '?' . $cgi->query_string);
66 } else {
67   print $cgi->redirect($redirect_ok . '?' .$pkey_val);
68 }
69 %>