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