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