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