89f0fcc4cf44d4a86f42aca6ff8f65ded430bfb8
[freeside.git] / httemplate / edit / elements / edit.html
1 <%doc>
2
3 Example:
4
5   include( 'elements/edit.html',  
6     'name_singular' =>  #singular name for the record
7                         # (preferred, will be pluralized automatically)
8     'name'          =>  #name for the record
9                         # (deprecated, will be pluralized simplistically)
10     'table'         =>
11
12     #? 'primary_key' => #required when the dbdef doesn't know...???
13     'labels' => {
14                   'column' => 'Label',
15                 }
16    
17     #listref - each item is a literal column name (or method) or hashref
18     #                                                        or (notyet) coderef
19     #if not specified all columns (except for the primary key) will be editable
20     'fields' => [
21                   'columname',
22                   { 'field' => 'another_columname',
23                     'type'  => 'text', #text
24                                        #password
25                                        #money
26                                        #percentage
27                                        #checkbox
28                                        #select
29                                        #selectlayers (can now use after a tablebreak-tr-title... but not inside columnstart/columnnext/columnend)
30                                        #title
31                                        #tablebreak-tr-title
32                                        #columnstart
33                                        #columnnext
34                                        #columnend
35                                        #hidden - hidden value from object
36                                        #fixed - display fixed value from object or here
37                                        #fixed-country
38                                        #fixed-state
39                     'value' => 'Y', #for checkbox, title, fixed, hidden
40                     'disabled' => 0,
41                     'onchange' => 'javascript_function',
42
43                     'include_opt_callback' => sub { my $object = @_;
44                                                     ( 'option' => 'value', );
45                                                   },
46
47                     'm2name_table'   => 'table_name',
48                     'm2name_namecol' => 'name_column',
49                     #OR#
50                     'm2m_method'       =>
51                     #'m2m_srccol'  => #opt, if not the same as this table
52                     'm2m_dstcol'  => #required for now, eventuaully opt, if not the same as target table
53                     #OR#
54                     'o2m_table' =>
55
56                     'm2_label'   => 'Label',        #
57                     'm2_new_default' => \@table_name_objects, #default
58                                                               #m2 objects for
59                                                               #new records
60                     'm2_error_callback' => sub { my($cgi, $object) = @_; },
61                     'm2_remove_warnings' => \%warnings, #hashref of warning
62                                                         #messages for m2
63                                                         #removal
64                     'm2_new_js' => 'function_name', #javascript function called
65                                                     #on spawned rows (one arg:
66                                                     #new_element)
67                     'm2_remove_js' => 'function_name', #js function called when
68                                                        #a row is deleted (three
69                                                        #args: value, text,
70                                                        #'no_match')
71                     #layer_fields & layer_values_callback only for selectlayer
72                     'layer_fields' => [
73                                         'fieldname'     => 'Label',
74                                         'another_field' => {
75                                           label=>'Label',
76                                           type =>'text', #text, money
77                                         },
78                                       ],
79                     'layer_values_callback' =>
80                       sub {
81                             my( $cgi, $object ) = @_;
82                             { 'layer'  => { 'fieldname'  => 'current_value',
83                                             'fieldname2' => 'field2value',
84                                             ...
85                                           },
86                               'layer2' => { 'l2fieldname' => 'l2value',
87                                             ...
88                                           },
89                               ...
90                             };
91                           },
92                   },
93                 ]
94    
95     'menubar'     => '', #menubar arrayref
96
97     #agent virtualization
98     'agent_virt'            => 1,
99     'agent_null'            => 1, #if true, always allow no-agentnum globals
100     'agent_null_right'      => 'Access Right Name',
101     'agent_clone_extra_sql' => '', #if provided, this overrides the extra_sql
102                                    #implementing agent virt, for clone
103                                    #operations.  i.e. pass "1=1" to allow
104                                    #cloning anything
105
106     'viewall_dir' => '', #'search' or 'browse', defaults to 'search'
107
108     # overrides default popurl(1)."process/$table.html"
109     'post_url' => popurl(1).'process/something', 
110
111     #we're in a popup (no title/menu/searchboxes)
112     'popup' => 1,
113
114     ###
115     # HTML callbacks
116     ###
117
118     'body_etc' => '', # Additional BODY attributes, i.e. onLoad=""
119
120     'html_init'   => '', #after the header/menubar
121
122     #string or coderef of additional HTML to add before </TABLE>
123     'html_table_bottom' => '',
124
125     #after </TABLE> but before the submit
126     'html_bottom' => '', #string
127     'html_bottom' => sub {
128                            my $object = shift;
129                            # ...
130                            "html_string";
131                          },
132     
133     #javascript function name, will be called with form name as arg
134     'onsubmit'   => 'check_form_data',
135
136     #at the very bottom (well, as low as you can go from here)
137     'html_foot'  => '',
138
139     ###
140     # initialization callbacks
141     ###
142
143     ###global callbacks, always run if provided
144
145     #after decoding long CGI "redirect=" responses but
146     # before object creation/search
147     # (useful if you have a long form that might trigger redirect= and you need
148     #  to do things with $cgi params - they're not decoded in the calling
149     #  <%init> block yet)
150     'begin_callback' = sub { my( $cgi, $fields_listref, $opt_hashref ) = @_; },
151
152     #after the mode-specific object creation/search
153     'end_callback' = sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
154
155     ###mode-specific callbacks.  one (and only one) of these four is called
156    
157     #run when adding
158     'new_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
159
160     #run when editing
161     'edit_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
162
163     #run when re-displaying with an error
164     'error_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
165    
166     #run when cloning
167     'clone_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
168
169     ###callbacks called in new mode only
170
171     # returns a hashref for the new object
172     'new_hashref_callback'
173
174     # returns the new object iself (otherwise, ->new is called)
175     'new_object_callback'
176
177     ###display callbacks
178
179     #run before display to return a different value
180     'value_callback' => sub { my( $columname, $value ) = @_; },
181
182     #run before display to manipulate element of the 'fields' arrayref
183     'field_callback' => sub { my( $cgi, $object, $field_hashref ) = @_; },
184
185   );
186
187 </%doc>
188
189 <% include('/elements/header'. ( $opt{popup} ? '-popup' : '' ). '.html',
190               $title,
191               include( '/elements/menubar.html', @menubar ),
192               $opt{'body_etc'},
193            )
194 %>
195
196 <% defined($opt{'html_init'}) 
197       ? ( ref($opt{'html_init'})
198             ? &{$opt{'html_init'}}()
199             : $opt{'html_init'}
200         )
201       : ''
202 %>
203
204 <% include('/elements/error.html') %>
205
206 % my $url = $opt{'post_url'} || popurl(1)."process/$table.html";
207
208 <FORM NAME   = "edit_topform"
209       METHOD = POST
210       ACTION = "<% $url %>"
211       <% $opt{onsubmit} ? 'onSubmit="return '.$opt{onsubmit}.'(this)"' : '' %>
212 >
213
214 <INPUT TYPE="hidden" NAME="svcdb" VALUE="<% $table %>">
215 <INPUT TYPE="hidden" NAME="<% $pkey %>" VALUE="<% $clone ? '' : $object->$pkey() %>">
216
217 <FONT SIZE="+1"><B>
218 <% ( $opt{labels} && exists $opt{labels}->{$pkey} )
219       ? $opt{labels}->{$pkey}
220       : $pkey
221 %>
222 </B></FONT>
223 #<% ( !$clone && $object->$pkey() ) || "(NEW)" %>
224
225 % my $tablenum = 0;
226 <TABLE ID="TableNumber<% $tablenum++ %>" BGCOLOR="#cccccc" BORDER=0 CELLSPACING=0>
227
228 % my $g_row = 0;
229 % my @g_row_stack = ();
230 % foreach my $f ( map { ref($_) ? $_ : {'field'=>$_} }
231 %                       @$fields
232 %                 ) {
233 %
234 %   my $trash = &{ $opt{'field_callback'} }( $cgi, $object, $f )
235 %     if $opt{'field_callback'};
236 %
237 %   my $field = $f->{'field'};
238 %   my $type = $f->{'type'} ||= 'text';
239 %
240 %   my $label = ( $opt{labels} && exists $opt{labels}->{$field} )
241 %                   ? $opt{labels}->{$field}
242 %                   : $field;
243 %
244 %   my $onchange = $f->{'onchange'};
245 %
246 %   my $layer_values = {};
247 %   $layer_values = &{ $f->{'layer_values_callback'} }( $cgi, $object )
248 %     if $f->{'layer_values_callback'}
249 %     && ! $f->{'m2name_table'}
250 %     && ! $f->{'o2m_table'}
251 %     && ! $f->{'m2m_method'};
252 %
253 %   warn "layer values: ". Dumper($layer_values)
254 %     if $opt{'debug'};
255 %
256 %   my %include_common = (
257 %
258 %     #text and derivitives
259 %     'size'          => $f->{'size'},
260 %     'maxlength'     => $f->{'maxlength'},
261 %     'postfix'       => $f->{'postfix'},
262 %
263 %     #checkbox, title, fixed, hidden
264 %     #& deprecated weird value hashref used only by reason.html
265 %     'value'         => $f->{'value'},
266 %
267 %     #select(-*)
268 %     'options'       => $f->{'options'},
269 %     'labels'        => $f->{'labels'},
270 %     'multiple'      => $f->{'multiple'},
271 %     'disable_empty' => $f->{'disable_empty'},
272 %     #select-reason
273 %     'reason_class'  => $f->{'reason_class'},
274 %
275 %     #selectlayers
276 %     'layer_fields'  => $f->{'layer_fields'},
277 %     'layer_values'  => $layer_values,
278 %     'html_between'  => $f->{'html_between'},
279 %
280 %     #umm.  for select-agent_types at least
281 %     'disabled'      => $f->{'disabled'},
282 %   );
283 %
284 %   #selectlayers, others?
285 %   $include_common{$_} = $f->{$_}
286 %     foreach grep exists($f->{$_}),
287 %                  qw( js_only html_only select_only layers_only cell_style);
288 %
289 %   #select-*
290 %   $include_common{$_} = $f->{$_}
291 %     foreach grep exists($f->{$_}), qw( empty_label );
292 %
293 %   #select-table
294 %   $include_common{$_} = $f->{$_}
295 %     foreach grep exists($f->{$_}), qw( value_col );
296 %   $include_common{$_} = ref( $f->{$_} ) eq 'CODE'
297 %                           ? &{ $f->{$_} }( $cgi, $object ) #, $f )
298 %                           : $f->{$_}
299 %     foreach grep exists($f->{$_}), qw( extra_sql );
300 %
301 %   #select-table, checkboxes-table
302 %   $include_common{$_} = $f->{$_}
303 %     foreach grep exists($f->{$_}), qw( table name_col  );
304 %
305 %   #checkboxes-table
306 %   $include_common{$_} = $f->{$_}
307 %     foreach grep exists($f->{$_}), qw( target_table link_table );
308 %
309 %   #*-table
310 %   $include_common{$_} = $f->{$_}
311 %     foreach grep exists($f->{$_}),
312 %       qw( hashref agent_virt agent_null agent_null_right );
313 %
314 %   #htmlarea
315 %   $include_common{$_} = $f->{$_}
316 %     foreach grep exists($f->{$_}), qw( width height );
317 %
318 %
319 %   if ( $type eq 'tablebreak-tr-title' ) {
320 %     $include_common{'table_id'} = 'TableNumber'. $tablenum++;
321 %   }
322 %   if ( $type eq 'tablebreak-tr-title' || $type eq 'title' ) {
323 %     $include_common{'colspan'} = $f->{colspan} if $f->{colspan};
324 %   }
325 %
326 %   if ( $f->{include_opt_callback} ) {
327 %     %include_common = ( %include_common,
328 %                         &{ $f->{include_opt_callback} }( $object )
329 %                       );
330 %   }
331 %
332 %   my $layer_prefix_on = '';
333 %
334 %   my $include_sub = sub {
335 %     my %opt = @_;
336 %
337 %     my $fieldnum   = delete $opt{'fieldnum'};
338 %
339 %     my $include = $type;
340 %     $include = "input-$include" if $include =~ /^(text|money|percentage)$/;
341 %     $include = "tr-$include" unless $include =~ /^(hidden|tablebreak|column)/;
342 %
343 %     $include_common{'layer_prefix'} = "$field$fieldnum."
344 %       if $layer_prefix_on;
345 %
346 %     my @include = 
347 %     ( "/elements/$include.html",
348 %         'field'      => "$field$fieldnum",
349 %         'id'         => "$field$fieldnum", #separate?
350 %         'label_id'   => $field."_label$fieldnum", #don't want field0_label0...
351 %         %include_common,
352 %         %opt,
353 %     );
354 %
355 %     if ( $include eq 'tr-input-date-field' ) {
356 %       # it's either hacking it here, or changing a lot more stuff
357 %       @include = (
358 %               "/elements/$include.html", {
359 %                       'name' => $field,
360 %                       'value' => $opt{curr_value},
361 %                       'label' => $label,
362 %                       'noinit' => $f->{noinit},
363 %               }
364 %       );
365 %     }
366 %
367 %     @include;
368 %   };
369 %
370 %   my $column_sub = sub {
371 %     my %opt = @_;
372 %
373 %     my $column   = delete($opt{field});
374 %     my $fieldnum = delete($opt{fieldnum});
375 %     my $include  = delete($opt{type}) || 'text';
376 %     $include = "input-$include" if $include =~ /^(text|money|percentage)$/;
377 %
378 %     ( "/elements/$include.html",
379 %         'field'        => $field.'__'.$column.$fieldnum,
380 %         'id'           => $field.'__'.$column.$fieldnum,
381 %         'layer_prefix' => $field.'__'.$column.$fieldnum.".",
382 %         ( $fieldnum
383 %             ? ('cell_style' => 'border-top:1px solid black')
384 %             : ()
385 %         ),
386 %         'cgi' => $cgi,
387 %         %opt,
388 %     );
389 %   };
390 %
391 %   unless ( $type =~ /^column/ ) {
392 %     $g_row = 1 if $type eq 'tablebreak-tr-title';
393 %     $g_row++;
394 %     $g_row++ if $type eq 'title';
395 %   } else {
396 %     if ( $type eq 'columnstart' ) {
397 %       push @g_row_stack, $g_row;
398 %       $g_row = 0;
399 %     #} elsif ( $type eq 'columnnext' ) {
400 %     } elsif ( $type eq 'columnend' ) {
401 %       $g_row = pop @g_row_stack; 
402 %     }
403 %  
404 %   }
405 %
406 %   my $fieldnum = '';
407 %   my $curr_value = '';
408 %   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
409 %
410 %     my($table, $col);
411 %     if ( $f->{'m2name_table'} ) {
412 %       $table = $f->{'m2name_table'};
413 %       $col   = $f->{'m2name_namecol'};
414 %     } elsif ( $f->{'o2m_table'} ) {
415 %       $table = $f->{'o2m_table'};
416 %       $col   = dbdef->table($f->{'o2m_table'})->primary_key;
417 %     } elsif ( $f->{'m2m_method'} ) {
418 %       $table = $f->{'m2m_method'};
419 %       $col   = $f->{'m2m_dstcol'};
420 %     }
421 %     $fieldnum = 0;
422 %     $layer_prefix_on = 1;
423 %     #print out the fields for the existing m2s
424 %     my @existing = ();
425 %     if ( $mode eq 'error' ) {
426 %       @existing = &{ $f->{'m2_error_callback'} }( $cgi, $object );
427 %     } elsif ( $object->$pkey() ) { # $mode eq 'edit'||'clone'
428 %       @existing = $object->$table();
429 %       warn scalar(@existing). " from $object->$table: ". join('/', @existing)
430 %         if $opt{'debug'};
431 %     } elsif ( $f->{'m2_new_default'} ) { # && $mode eq 'new'
432 %       @existing = @{ $f->{'m2_new_default'} };
433 %     }
434 %     foreach my $name_obj ( @existing ) {
435 %
436 %       my $ex_label = '<INPUT TYPE="button" VALUE="X" TITLE="Remove this '.
437 %                      lc($f->{'m2_label'}).
438 %                      qq(" onClick="remove_$field($fieldnum);").
439 %                      ' STYLE="color:#ff0000;font-weight:bold;'.
440 %                              'padding-left:2px;padding-right:2px"'.
441 %                      '>&nbsp;'. ($f->{'m2_label'} || $field ). ' ';
442 %       
443 %       if ( $f->{'layer_values_callback'} ) {
444 %         my %switches = ( 'mode' => $mode );
445 %         $layer_values =
446 %           &{ $f->{'layer_values_callback'} }( $cgi, $name_obj, \%switches );
447 %       }
448 %       warn "layer values: ". Dumper($layer_values)
449 %         if $opt{'debug'};
450 %
451 %       my @existing = &{ $include_sub }(
452 %         'label'        => $ex_label,
453 %         'fieldnum'     => $fieldnum,
454 %         'curr_value'   => $name_obj->$col(),
455 %         'onchange'     => $onchange,
456 %         'layer_values' => $layer_values,
457 %         'cell_style'   => ( $fieldnum ? 'border-top:1px solid black' : '' ),
458 %       );
459 %       $existing[0] =~ s(^/elements/tr-)(/elements/);
460 %       my @label = @existing;
461 %       $label[0] = '/elements/tr-td-label.html';
462
463         <% include( @label ) %>
464         <TD COLSPAN="<% $f->{'colspan'} || 1 %>">
465         <% include( @existing ) %>
466         </TD>
467
468 %       if ( $f->{'m2_fields'} ) {
469 %         foreach my $c ( @{ $f->{'m2_fields'} } ) {
470 %           my $column = $c->{field};
471 %           my @column = &{ $column_sub }( %$c,
472 %                                          'fieldnum' => $fieldnum,
473 %                                          'curr_value' => $name_obj->$column()
474 %                                        );
475
476             <TD id='<% $field %>__<% $column %>_label<% $fieldnum %>'
477                 style='text-align:right;vertical-align:top;
478                        border-top:1px solid black;padding-top:5px;'>
479               <% $c->{'label'} || '' %>
480             </TD>
481             <TD style='border-top:1px solid black;padding-top:3px;'>
482               <% include( @column ) %>
483             </TD>
484 %         }
485 %       }
486
487         </TR>
488
489 %       $fieldnum++;
490 %       $g_row++;
491 %     }
492 %     #$field .= $fieldnum;
493 %     $onchange .= "\nspawn_$field(what);";
494 %   } else {
495 %     if ( $f->{curr_value_callback} ) {
496 %       $curr_value = &{ $f->{curr_value_callback} }( $cgi, $object, $field ),
497 %     } else {
498 %       $curr_value = $object->$field();
499 %     }
500 %     $curr_value = &{ $opt{'value_callback'} }( $f->{'field'}, $curr_value )
501 %       if $opt{'value_callback'} && $mode ne 'error';
502 %   }
503 %
504 %   my @include = &{ $include_sub }(
505 %     'label'      => $label,
506 %     'fieldnum'   => $fieldnum,
507 %     'curr_value' => $curr_value,
508 %     'object'     => $object,
509 %     'cgi'        => $cgi,
510 %     'onchange'   => $onchange,
511 %     ( $fieldnum ? ('cell_style' => 'border-top:1px solid black') : () ),
512 %   );
513 %
514 %   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
515 %     $include[0] =~ s(^/elements/tr-)(/elements/);
516 %     my @label = @include;
517 %     $label[0] = '/elements/tr-td-label.html';
518
519       <% include( @label ) %>
520       <TD COLSPAN="<% $f->{'colspan'} || 1 %>">
521       <% include( @include ) %>
522       </TD>
523
524 %     if ( $f->{'m2_fields'} ) {
525 %       foreach my $c ( @{ $f->{'m2_fields'} } ) {
526 %         my $column = $c->{field};
527 %         my @column = &{ $column_sub }( %$c, 'fieldnum' => $fieldnum );
528
529           <TD id='<% $field %>__<% $column %>_label<% $fieldnum %>'
530               style='text-align:right;vertical-align:top;
531                      border-top:1px solid black;padding-top:5px;'>
532             <% $c->{'label'} || '' %>
533           </TD>
534           <TD style='border-top:1px solid black;padding-top:3px;'>
535             <% include( @column ) %>
536           </TD>
537 %       }
538 %     }
539
540       </TR>
541
542 %   } else {
543
544       <% include( @include ) %>
545
546 %   }
547 %   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
548
549       <SCRIPT TYPE="text/javascript">
550
551         var <%$field%>_rownum = <% $g_row %>;
552         var <%$field%>_fieldnum = <% $fieldnum %>;
553
554         function spawn_<%$field%>(what) {
555
556           // only spawn if we're the last element... return if not
557
558           var field_regex = /(\d+)(_[a-z]+)?$/;
559           var match = field_regex.exec(what.name);
560           if ( !match ) {
561             alert(what.name + " didn't match for " + what);
562             return;
563           }
564           if ( match[1] != <%$field%>_fieldnum ) {
565             return;
566           }
567
568           // change the label on the last entry & add a remove button
569           var prev_label = document.getElementById('<% $field %>_label' + <%$field%>_fieldnum );
570           prev_label.innerHTML = '<INPUT TYPE="button" VALUE="X" TITLE="Remove this <% lc($f->{'m2_label'}) %>" onClick="remove_<% $field %>(' + <%$field%>_fieldnum + ');" STYLE="color:#ff0000;font-weight:bold;padding-left:2px;padding-right:2px" >&nbsp;<% $f->{'m2_label'} || $field %>';
571
572           <%$field%>_fieldnum++;
573
574           //get the new widget
575
576 %         $include[0] =~ s(^/elements/tr-)(/elements/);
577 %         my @layer_opt = ( @include,
578 %                           'field'        => $field."MAGIC_NUMBER",
579 %                           'id'           => $field."MAGIC_NUMBER",
580 %                           'layer_prefix' => $field."MAGIC_NUMBER.",
581 %                         );
582 %         warn @layer_opt if $opt{'debug'};
583
584           var newrow =  <% include(@layer_opt, html_only=>1) |js_string %>;
585
586 %         #until the rest have html/js_only
587 %         if ( $type eq 'selectlayers' || $type =~ /^select-cgp_rule_/ ) {
588             var newfunc = <% include(@layer_opt, js_only=>1) |js_string %>;
589 %         } else {
590             var newfunc = '';
591 %         }
592
593           // substitute in the new field name
594           var magic_regex = /MAGIC_NUMBER/g;
595           newrow  = newrow.replace(  magic_regex, <%$field%>_fieldnum );
596           newfunc = newfunc.replace( magic_regex, <%$field%>_fieldnum );
597
598           // evaluate new_func
599           if (window.ActiveXObject) {
600             window.execScript(newfunc);
601           } else { /* (window.XMLHttpRequest) */
602             //window.eval(newfunc);
603             setTimeout(newfunc, 0);
604           }
605
606           // add new row
607
608           //hmm, can't use selectlayers after a tablebreak-title for now
609           var table = document.getElementById('TableNumber<% $tablenum-1 %>');
610
611           var row = table.insertRow(<%$field%>_rownum++);
612
613           var label_cell = document.createElement('TD');
614
615           label_cell.id = '<% $field %>_label' + <%$field%>_fieldnum;
616
617           label_cell.style.textAlign = "right";
618           label_cell.style.verticalAlign = "top";
619           label_cell.style.borderTop = "1px solid black";
620           label_cell.style.paddingTop = "5px";
621
622           label_cell.innerHTML = '<% $label %>';
623
624           row.appendChild(label_cell);
625           
626           var widget_cell = document.createElement('TD');
627
628           widget_cell.style.borderTop = "1px solid black";
629           widget_cell.style.paddingTop = "3px";
630           widget_cell.colSpan = "<% $f->{'colspan'} || 1 %>"
631
632           widget_cell.innerHTML = newrow;
633
634           row.appendChild(widget_cell);
635
636 %         if ( $f->{'m2_fields'} ) {
637 %           foreach my $c ( @{ $f->{'m2_fields'} } ) {
638 %             my $column = $c->{field};
639 %             my @column = &{ $column_sub }(%$c, 'fieldnum' => 'MAGIC_NUMBER');
640
641               var column =  <% include(@column, html_only=>1) |js_string %>;
642               column  = column.replace(  magic_regex, <%$field%>_fieldnum );
643
644               var column_label = document.createElement('TD');
645               column_label.id =
646                 '<% $field %>__<% $column %>_label' + <%$field%>_fieldnum;
647
648               column_label.style.textAlign = "right";
649               column_label.style.verticalAlign = "top";
650               column_label.style.borderTop = "1px solid black";
651               column_label.style.paddingTop = "5px";
652
653               column_label.innerHTML = '<% $c->{'label'} || '' %>';
654
655               row.appendChild(column_label);
656           
657               var column_widget = document.createElement('TD');
658
659               column_widget.style.borderTop = "1px solid black";
660               column_widget.style.paddingTop = "3px";
661
662               column_widget.innerHTML = column;
663
664               row.appendChild(column_widget);
665
666 %           }
667 %         }
668
669 %         if ( $f->{'m2_new_js'} ) {
670             // take out items selected in previous dropdowns
671             var new_element = document.getElementById("<%$field%>" + <%$field%>_fieldnum );
672             <% $f->{'m2_new_js'} %>(new_element);
673
674             if ( new_element.length < 2 ) {
675               //just the ** Select new **, so don't display the row
676               row.style.display = 'none';
677             }
678 %         }
679
680         }
681
682         function remove_<%$field%>(remove_fieldnum) {
683           //alert("remove <%$field%> " + remove_fieldnum);
684           var select = document.getElementById('<%$field%>' + remove_fieldnum);
685
686           if ( ! select ) {
687             alert("can't find element <%$field%>" + remove_fieldnum);
688             return;
689           }
690
691 %         my $warnings = $f->{'m2_remove_warnings'};
692 %         if ( $warnings ) {
693             var sel_value = select.options[select.selectedIndex].value;
694 %           foreach my $value ( keys %$warnings ) {
695               if ( sel_value == '<% $value %>' ) {
696                 if ( ! confirm( <% $warnings->{$value} |js_string %> ) ) {
697                   return;
698                 }
699               }
700 %           }
701 %         }
702
703           select.disabled = 'disabled'; // this seems to prevent it from being submitted on tested browsers so far (IE, moz, konq at least)
704           var label_td = document.getElementById('<%$field%>_label' + remove_fieldnum );
705           label_td.parentNode.style.display = 'none';
706
707 %         if ( $f->{m2_remove_js} ) {
708             var opt = select.options[select.selectedIndex];
709             <% $f->{m2_remove_js} %>( opt.value, opt.text, 'no_match');
710 %         }
711
712         }
713
714       </SCRIPT>
715
716 %   }
717
718 % } 
719
720 <% ref( $opt{'html_table_bottom'} )
721       ? &{ $opt{'html_table_bottom'} }( $object )
722       : $opt{'html_table_bottom'}
723 %>
724
725 </TABLE>
726
727 <% ref( $opt{'html_bottom'} )
728       ? &{ $opt{'html_bottom'} }( $object )
729       : $opt{'html_bottom'}
730 %>
731
732 <BR>
733
734 <INPUT TYPE     = "submit"
735        ID       = "submit"
736        VALUE    = "<% ( !$clone && $object->$pkey() )
737                         ? "Apply changes"
738                         : "Add ". ( $opt{'name'} || $opt{'name_singular'} )
739                    %>"
740 >
741
742 </FORM>
743
744 <% ref( $opt{'html_foot'} )
745       ? &{ $opt{'html_foot'} }( $object )
746       : $opt{'html_foot'}
747 %>
748
749 <% include("/elements/footer.html") %>
750 <%init>
751
752 my(%opt) = @_;
753
754 my $curuser = $FS::CurrentUser::CurrentUser;
755
756 #false laziness w/process.html
757 my $table = $opt{'table'};
758 my $class = "FS::$table";
759 my $pkey = dbdef->table($table)->primary_key; #? $opt{'primary_key'} || 
760 my $fields = $opt{'fields'}
761              #|| [ grep { $_ ne $pkey } dbdef->table($table)->columns ];
762              || [ grep { $_ ne $pkey } fields($table) ];
763 #my @actualfields = map { ref($_) ? $_->{'field'} : $_ } @$fields;
764
765 if ( $cgi->param('redirect') ) {
766   my $session = $cgi->param('redirect');
767   my $pref = $curuser->option("redirect$session");
768   die "unknown redirect session $session\n" unless length($pref);
769   $cgi = new CGI($pref);
770 }
771
772 &{$opt{'begin_callback'}}( $cgi, $fields, \%opt )
773   if $opt{'begin_callback'};
774
775 my %qsearch = (
776     'table'     => $table,
777     'extra_sql' => ( $opt{'agent_virt'}
778                        ? ' AND '. $curuser->agentnums_sql(
779                                     'null_right' => $opt{'agent_null_right'}
780                                   )
781                        : ''
782                    ),
783 );
784
785 my $mode;
786 my $object;
787 my $clone = '';
788 if ( $cgi->param('error') ) {
789
790   $mode = 'error';
791
792   $object = $class->new( {
793     map { $_ => scalar($cgi->param($_)) } fields($table)
794   });
795
796   &{$opt{'error_callback'}}( $cgi, $object, $fields, \%opt )
797     if $opt{'error_callback'};
798
799 } elsif ( $cgi->param('clone') =~ /^(\d+)$/ ) {
800
801   $mode = 'clone';
802
803   $clone = $1;
804
805   $qsearch{'extra_sql'} = ' AND '. $opt{'agent_clone_extra_sql'}
806     if $opt{'agent_clone_extra_sql'};
807
808   $object = qsearchs({ %qsearch, 'hashref' => { $pkey => $clone } })
809     or die "$pkey $clone not found in $table";
810
811   &{$opt{'clone_callback'}}( $cgi, $object, $fields, \%opt )
812     if $opt{'clone_callback'};
813
814   #$object->$pkey('');
815
816   $opt{action} ||= 'Add';
817
818 } elsif ( $cgi->keywords || $cgi->param($pkey) ) { #editing
819
820   $mode = 'edit';
821
822   my $value;
823   if ( $cgi->param($pkey) ) {
824     $value = $cgi->param($pkey)
825   } else { 
826     my( $query ) = $cgi->keywords;
827     $value = $query;
828   }
829   $value =~ /^(\d+)$/ or die "unparsable $pkey";
830   $object = qsearchs({ %qsearch, 'hashref' => { $pkey => $1 } })
831     or die "$pkey $1 not found in $table";
832   
833   warn "$table $pkey => $1"
834     if $opt{'debug'};
835
836   &{$opt{'edit_callback'}}( $cgi, $object, $fields, \%opt )
837     if $opt{'edit_callback'};
838
839 } else { #adding
840
841   $mode = 'new';
842
843   my $hashref = $opt{'new_hashref_callback'}
844                   ? &{$opt{'new_hashref_callback'}}
845                   : {};
846
847   $object = $opt{'new_object_callback'}
848               ? &{$opt{'new_object_callback'}}( $cgi, $hashref, $fields, \%opt )
849               : $class->new( $hashref );
850
851   &{$opt{'new_callback'}}( $cgi, $object, $fields, \%opt )
852     if $opt{'new_callback'};
853
854 }
855
856 &{$opt{'end_callback'}}( $cgi, $object, $fields, \%opt )
857   if $opt{'end_callback'};
858
859 $opt{action} ||= $object->$pkey() ? 'Edit' : 'Add';
860
861 my $title = $opt{action}. ' '. ( $opt{name} || $opt{'name_singular'} );
862
863 my $viewall_url = $p . ( $opt{'viewall_dir'} || 'search' ) . "/$table.html";
864 $viewall_url = $opt{'viewall_url'} if $opt{'viewall_url'};  
865
866 my @menubar = ();
867 if ( $opt{'menubar'} ) {
868   @menubar = @{ $opt{'menubar'} };
869 } else {
870   my $items = $opt{'name'} ? $opt{'name'}.'s' : PL($opt{'name_singular'});
871   @menubar = (
872     "View all $items" => $viewall_url,
873   );
874 }
875
876 </%init>