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