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