summaryrefslogtreecommitdiff
path: root/httemplate/edit/elements/edit.html
blob: d18a37d5a7a356ca6aba6ba8dda3b1dfc5054e5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
<%doc>

Example:

  include( 'elements/edit.html',  
    'name_singular' =>  #singular name for the record
                        # (preferred, will be pluralized automatically)
    'name'          =>  #name for the record
                        # (deprecated, will be pluralized simplistically)
    'table'         =>

    #? 'primary_key' => #required when the dbdef doesn't know...???
    'labels' => {
                  'column' => 'Label',
                }
   
    #listref - each item is a literal column name (or method) or hashref
    #                                                        or (notyet) coderef
    #if not specified all columns (except for the primary key) will be editable
    'fields' => [
                  'columname',
                  { 'field' => 'another_columname',
                    'type'  => 'text', #text
                                       #password
                                       #money
                                       #percentage
                                       #checkbox
                                       #select
                                       #selectlayers (can now use after a tablebreak-tr-title... but not inside columnstart/columnnext/columnend)
                                       #title
                                       #tablebreak-tr-title
                                       #columnstart
                                       #columnnext
                                       #columnend
                                       #hidden - hidden value from object
                                       #fixed - display fixed value from object or here
                                       #fixed-country
                                       #fixed-state
                    'value' => 'Y', #for checkbox, title, fixed, hidden
                    'disabled' => 0,
                    'onchange' => 'javascript_function',

                    #m2 stuff only tested w/selectlayers so far
                    #might work w/select too, dunno others
                    'm2name_table'   => 'table_name',
                    'm2name_namecol' => 'name_column',
                    #OR#
                    'm2m_method'       =>
                    #'m2m_srccol'  => #opt, if not the same as this table
                    'm2m_dstcol'  => #required for now, eventuaully opt, if not the same as target table

                    'm2_label'   => 'Label',        #
                    'm2_new_default' => \@table_name_objects, #default
                                                              #m2 objects for
                                                              #new records
                    'm2_error_callback' => sub { my($cgi, $object) = @_; },
                    'm2_remove_warnings' => \%warnings, #hashref of warning
                                                        #messages for m2
                                                        #removal
                    'm2_new_js' => 'function_name', #javascript function called
                                                    #on spawned rows (one arg:
                                                    #new_element)
                    'm2_remove_js' => 'function_name', #js function called when
                                                       #a row is deleted (three
                                                       #args: value, text,
                                                       #'no_match')
                    #layer_fields & layer_values_callback only for selectlayer
                    'layer_fields' => [
                                        'fieldname'     => 'Label',
                                        'another_field' => {
                                          label=>'Label',
                                          type =>'text', #text, money
                                        },
                                      ],
                    'layer_values_callback' =>
                      sub {
                            my( $cgi, $object ) = @_;
                            { 'layer'  => { 'fieldname'  => 'current_value',
                                            'fieldname2' => 'field2value',
                                            ...
                                          },
                              'layer2' => { 'l2fieldname' => 'l2value',
                                            ...
                                          },
                              ...
                            };
                          },
                  },
                ]
   
    'menubar'     => '', #menubar arrayref

    #agent virtualization
    'agent_virt'            => 1,
    'agent_null_right'      => 'Access Right Name',
    'agent_clone_extra_sql' => '', #if provided, this overrides the extra_sql
                                   #implementing agent virt, for clone
                                   #operations.  i.e. pass "1=1" to allow
                                   #cloning anything

    'viewall_dir' => '', #'search' or 'browse', defaults to 'search'

    # overrides default popurl(1)."process/$table.html"
    'post_url' => popurl(1).'process/something', 

    #we're in a popup (no title/menu/searchboxes)
    'popup' => 1,

    ###
    # HTML callbacks
    ###

    'body_etc' => '', # Additional BODY attributes, i.e. onLoad=""

    'html_init'   => '', #after the header/menubar

    #string or coderef of additional HTML to add before </TABLE>
    'html_table_bottom' => '',

    #after </TABLE> but before the submit
    'html_bottom' => '', #string
    'html_bottom' => sub {
                           my $object = shift;
                           # ...
                           "html_string";
                         },
    
    #at the very bottom (well, as low as you can go from here)
    'html_foot'  => '',

    ###
    # initialization callbacks
    ###

    ###global callbacks

    #always run if provided, after decoding long CGI "redirect=" responses but
    # before object creation/search
    # (useful if you have a long form that might trigger redirect= and you need
    #  to do things with $cgi params - they're not decoded in the calling
    #  <%init> block yet)
    'begin_callback' = sub { my( $cgi, $fields_listref, $opt_hashref ) = @_; },

    #always run, after the mode-specific object creation/search
    'end_callback' = sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },

    ###mode-specific callbacks
   
    #run when re-displaying with an error
    'error_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
   
    #run when editing
    'edit_callback' => sub { my( $cgi, $object, $fields_listref ) = @_; },
   
    # returns a hashref for the new object
    'new_hashref_callback'

    # returns the new object iself (otherwise, ->new is called)
    'new_object_callback'
   
    #run when adding
    'new_callback' => sub { my( $cgi, $object, $fields_listref ) = @_; },

    #run when cloning
    'clone_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },

    ###display callbacks

    #run before display to return a different value
    'value_callback' => sub { my( $columname, $value ) = @_; },

    #run before display to manipulate element of the 'fields' arrayref
    'field_callback' => sub { my( $cgi, $object, $field_hashref ) = @_; },

  );

</%doc>

<% include('/elements/header'. ( $opt{popup} ? '-popup' : '' ). '.html',
              $title,
              include( '/elements/menubar.html', @menubar ),
              $opt{'body_etc'},
           )
%>

<% defined($opt{'html_init'}) 
      ? ( ref($opt{'html_init'})
            ? &{$opt{'html_init'}}()
            : $opt{'html_init'}
        )
      : ''
%>

<% include('/elements/error.html') %>

% my $url = $opt{'post_url'} || popurl(1)."process/$table.html";

<FORM ACTION="<% $url %>" METHOD=POST NAME="edit_topform">

<INPUT TYPE="hidden" NAME="svcdb" VALUE="<% $table %>">
<INPUT TYPE="hidden" NAME="<% $pkey %>" VALUE="<% $clone ? '' : $object->$pkey() %>">

<FONT SIZE="+1"><B>
<% ( $opt{labels} && exists $opt{labels}->{$pkey} )
      ? $opt{labels}->{$pkey}
      : $pkey
%>
</B></FONT>
#<% ( !$clone && $object->$pkey() ) || "(NEW)" %>

% my $tablenum = 0;
<TABLE ID="TableNumber<% $tablenum++ %>" BGCOLOR="#cccccc" BORDER=0 CELLSPACING=0>

% my $g_row = 0;
% my @g_row_stack = ();
% foreach my $f ( map { ref($_) ? $_ : {'field'=>$_} }
%                       @$fields
%                 ) {
%
%   my $trash = &{ $opt{'field_callback'} }( $cgi, $object, $f )
%     if $opt{'field_callback'};
%
%   my $field = $f->{'field'};
%   my $type = $f->{'type'} ||= 'text';
%
%   my $label = ( $opt{labels} && exists $opt{labels}->{$field} )
%                   ? $opt{labels}->{$field}
%                   : $field;
%
%   my $onchange = $f->{'onchange'};
%
%   my $layer_values = {};
%   $layer_values = &{ $f->{'layer_values_callback'} }( $cgi, $object )
%     if $f->{'layer_values_callback'}
%     && ! $f->{'m2name_table'}
%     && ! $f->{'m2m_method'};
%
%   warn "layer values: ". Dumper($layer_values)
%     if $opt{'debug'};
%
%   my %include_common = (
%
%     #text and derivitives
%     'size'          => $f->{'size'},
%     'maxlength'     => $f->{'maxlength'},
%
%     #checkbox, title, fixed, hidden
%     #& deprecated weird value hashref used only by reason.html
%     'value'         => $f->{'value'},
%
%     #select(-*)
%     'options'       => $f->{'options'},
%     'labels'        => $f->{'labels'},
%     'multiple'      => $f->{'multiple'},
%     'disable_empty' => $f->{'disable_empty'},
%     #select-reason
%     'reason_class'  => $f->{'reason_class'},
%
%     #selectlayers
%     'layer_fields'  => $f->{'layer_fields'},
%     'layer_values'  => $layer_values,
%     'html_between'  => $f->{'html_between'},
%
%     #umm.  for select-agent_types at least
%     'disabled'      => $f->{'disabled'},
%   );
%
%   #selectlayers, others?
%   $include_common{$_} = $f->{$_}
%     foreach grep exists($f->{$_}),
%                  qw( js_only html_only select_only layers_only cell_style);
%
%   #select-*
%   $include_common{$_} = $f->{$_}
%     foreach grep exists($f->{$_}), qw( empty_label );
%
%   #select-table, checkboxes-table
%   $include_common{$_} = $f->{$_}
%     foreach grep exists($f->{$_}), qw( table name_col );
%
%   #checkboxes-table
%   $include_common{$_} = $f->{$_}
%     foreach grep exists($f->{$_}), qw( target_table link_table );
%
%   #*-table
%   $include_common{$_} = $f->{$_}
%     foreach grep exists($f->{$_}), qw( hashref agent_virt agent_null_right );
%
%   if ( $type eq 'tablebreak-tr-title' ) {
%     $include_common{'table_id'} = 'TableNumber'. $tablenum++
%   }
%
%   my $layer_prefix_on = '';
%
%   my $include_sub = sub {
%     my %opt = @_;
%
%     my $fieldnum   = delete $opt{'fieldnum'};
%
%     my $include = $type;
%     $include = "input-$include" if $include =~ /^(text|money|percentage)$/;
%     $include = "tr-$include" unless $include =~ /^(hidden|tablebreak|column)/;
%
%     $include_common{'layer_prefix'} = "$field$fieldnum."
%       if $layer_prefix_on;
%
%     my @include = 
%     ( "/elements/$include.html",
%         'field'      => "$field$fieldnum",
%         'id'         => "$field$fieldnum", #separate?
%         'label_id'   => $field."_label$fieldnum", #don't want field0_label0...
%         %include_common,
%         %opt,
%     );
%     @include;
%   };
%
%   unless ( $type =~ /^column/ ) {
%     $g_row = 1 if $type eq 'tablebreak-tr-title';
%     $g_row++;
%     $g_row++ if $type eq 'title';
%   } else {
%     if ( $type eq 'columnstart' ) {
%       push @g_row_stack, $g_row;
%       $g_row = 0;
%     #} elsif ( $type eq 'columnnext' ) {
%     } elsif ( $type eq 'columnend' ) {
%       $g_row = pop @g_row_stack; 
%     }
%  
%   }
%
%   my $fieldnum = '';
%   my $curr_value = '';
%   if ( $f->{'m2name_table'} || $f->{'m2m_method'} ) { #XXX test this for all
%                                                      #types of fields
%     my($table, $col);
%     if ( $f->{'m2name_table'} ) {
%       $table = $f->{'m2name_table'};
%       $col   = $f->{'m2name_namecol'};
%     } elsif ( $f->{'m2m_method'} ) {
%       $table = $f->{'m2m_method'};
%       $col   = $f->{'m2m_dstcol'};
%     }
%     $fieldnum = 0;
%     $layer_prefix_on = 1;
%     #print out the fields for the existing m2s
%     my @existing = ();
%     if ( $mode eq 'error' ) {
%       @existing = &{ $f->{'m2_error_callback'} }( $cgi, $object );
%     } elsif ( $object->$pkey() ) { # $mode eq 'edit'||'clone'
%       @existing = $object->$table();
%      warn scalar(@existing). " from $object->$table: ". join('/', @existing)
%        if $opt{'debug'};
%     } elsif ( $f->{'m2_new_default'} ) { # && $mode eq 'new'
%       @existing = @{ $f->{'m2_new_default'} };
%     }
%     foreach my $name_obj ( @existing ) {
%
%       my $ex_label = '<INPUT TYPE="button" VALUE="X" TITLE="Remove this '.
%                      lc($f->{'m2_label'}).
%                      qq(" onClick="remove_$field($fieldnum);").
%                      ' STYLE="color:#ff0000;font-weight:bold;'.
%                              'padding-left:2px;padding-right:2px"'.
%                      '>&nbsp;'. ($f->{'m2_label'} || $field ). ' ';
%       
%       if ( $f->{'layer_values_callback'} ) {
%         my %switches = ( 'mode' => $mode );
%         $layer_values =
%           &{ $f->{'layer_values_callback'} }( $cgi, $name_obj, \%switches );
%       }
%       warn "layer values: ". Dumper($layer_values)
%         if $opt{'debug'};
%
%       my @existing = &{ $include_sub }(
%         'label'        => $ex_label,
%         'fieldnum'     => $fieldnum,
%         'curr_value'   => $name_obj->$col(),
%         'onchange'     => $onchange,
%         'layer_values' => $layer_values,
%         'cell_style'   => ( $fieldnum ? 'border-top:1px solid black' : '' ),
%       );

        <% include( @existing ) %>

%       $fieldnum++;
%       $g_row++;
%     }
%     #$field .= $fieldnum;
%     $onchange .= "\nspawn_$field(what);";
%   } else {
%     if ( $f->{curr_value_callback} ) {
%       $curr_value = &{ $f->{curr_value_callback} }( $cgi, $object, $field ),
%     } else {
%       $curr_value = $object->$field();
%     }
%     $curr_value = &{ $opt{'value_callback'} }( $f->{'field'}, $curr_value )
%       if $opt{'value_callback'} && $mode ne 'error';
%   }
%
%   my @include = &{ $include_sub }(
%     'label'      => $label,
%     'fieldnum'   => $fieldnum,
%     'curr_value' => $curr_value,
%     'object'     => $object,
%     'cgi'        => $cgi,
%     'onchange'   => $onchange,
%     ( $fieldnum ? ('cell_style' => 'border-top:1px solid black') : () ),
%   );

    <% include( @include ) %>

%   if ( $f->{'m2name_table'} || $f->{'m2m_method'} ) {

      <SCRIPT TYPE="text/javascript">

        var <%$field%>_rownum = <% $g_row %>;
        var <%$field%>_fieldnum = <% $fieldnum %>;

        function spawn_<%$field%>(what) {

          // only spawn if we're the last element... return if not

          var field_regex = /(\d+)$/;
          var match = field_regex.exec(what.name);
          if ( !match ) {
            alert(what.name + " didn't match?!");
            return;
          }
          if ( match[1] != <%$field%>_fieldnum ) {
            return;
          }

          // change the label on the last entry & add a remove button
          var prev_label = document.getElementById('<% $field %>_label' + <%$field%>_fieldnum );
          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 %>';

          <%$field%>_fieldnum++;

          //get the new widget

%         $include[0] =~ s(^/elements/tr-)(/elements/);
%         my @layer_opt = ( @include,
%                           'field'        => $field."MAGIC_NUMBER",
%                           'id'           => $field."MAGIC_NUMBER",
%                           'layer_prefix' => $field."MAGIC_NUMBER.",
%                         );
%         warn @layer_opt if $opt{'debug'};

          var newrow =  <% include(@layer_opt, html_only=>1) |js_string %>;

%         if ( $type eq 'selectlayers' ) { #until the rest have html/js_only
            var newfunc = <% include(@layer_opt, js_only  =>1) |js_string %>;
%         } else {
            var newfunc = '';
%         }

          // substitute in the new field name
          var magic_regex = /MAGIC_NUMBER/g;
          newrow  = newrow.replace(  magic_regex, <%$field%>_fieldnum );
          newfunc = newfunc.replace( magic_regex, <%$field%>_fieldnum );

          // evaluate new_func
          if (window.ActiveXObject) {
            window.execScript(newfunc);
          } else { /* (window.XMLHttpRequest) */
            //window.eval(newfunc);
            setTimeout(newfunc, 0);
          }

          // add new row

          //hmm, can't use selectlayers after a tablebreak-title for now
          var table = document.getElementById('TableNumber<% $tablenum-1 %>');

          var row = table.insertRow(<%$field%>_rownum++);

          var label_cell = document.createElement('TD');

          label_cell.id = '<% $field %>_label' + <%$field%>_fieldnum;

          label_cell.style.textAlign = "right";
          label_cell.style.verticalAlign = "top";
          label_cell.style.borderTop = "1px solid black";
          label_cell.style.paddingTop = "5px";

          label_cell.innerHTML = '<% $label %>';

          row.appendChild(label_cell);
          
          var widget_cell = document.createElement('TD');

          widget_cell.style.borderTop = "1px solid black";
          widget_cell.style.paddingTop = "3px";

          widget_cell.innerHTML = newrow;

          row.appendChild(widget_cell);

%         if ( $f->{'m2_new_js'} ) {
            // take out items selected in previous dropdowns
            var new_element = document.getElementById("<%$field%>" + <%$field%>_fieldnum );
            <% $f->{'m2_new_js'} %>(new_element);

            if ( new_element.length < 2 ) {
              //just the ** Select new **, so don't display the row
              row.style.display = 'none';
            }
%         }

        }

        function remove_<%$field%>(remove_fieldnum) {
          //alert("remove <%$field%> " + remove_fieldnum);
          var select = document.getElementById('<%$field%>' + remove_fieldnum);

          if ( ! select ) {
            alert("can't find element <%$field%>" + remove_fieldnum);
            return;
          }

%         my $warnings = $f->{'m2_remove_warnings'};
%         if ( $warnings ) {
            var sel_value = select.options[select.selectedIndex].value;
%           foreach my $value ( keys %$warnings ) {
              if ( sel_value == '<% $value %>' ) {
                if ( ! confirm( <% $warnings->{$value} |js_string %> ) ) {
                  return;
                }
              }
%           }
%         }

          select.disabled = 'disabled'; // this seems to prevent it from being submitted on tested browsers so far (IE, moz, konq at least)
          var label_td = document.getElementById('<%$field%>_label' + remove_fieldnum );
          label_td.parentNode.style.display = 'none';

%         if ( $f->{m2_remove_js} ) {
            var opt = select.options[select.selectedIndex];
            <% $f->{m2_remove_js} %>( opt.value, opt.text, 'no_match');
%         }

        }

      </SCRIPT>

%   }

% } 

<% ref( $opt{'html_table_bottom'} )
      ? &{ $opt{'html_table_bottom'} }( $object )
      : $opt{'html_table_bottom'}
%>

</TABLE>

<% ref( $opt{'html_bottom'} )
      ? &{ $opt{'html_bottom'} }( $object )
      : $opt{'html_bottom'}
%>

<BR>

<INPUT TYPE="submit" ID="submit" VALUE="<% ( !$clone && $object->$pkey() ) ? "Apply changes" : "Add $opt{'name'}" %>">

</FORM>

<% ref( $opt{'html_foot'} )
      ? &{ $opt{'html_foot'} }( $object )
      : $opt{'html_foot'}
%>

<% include("/elements/footer.html") %>
<%init>

my(%opt) = @_;

my $curuser = $FS::CurrentUser::CurrentUser;

#false laziness w/process.html
my $table = $opt{'table'};
my $class = "FS::$table";
my $pkey = dbdef->table($table)->primary_key; #? $opt{'primary_key'} || 
my $fields = $opt{'fields'}
             #|| [ grep { $_ ne $pkey } dbdef->table($table)->columns ];
             || [ grep { $_ ne $pkey } fields($table) ];
#my @actualfields = map { ref($_) ? $_->{'field'} : $_ } @$fields;

if ( $cgi->param('redirect') ) {
  my $session = $cgi->param('redirect');
  my $pref = $curuser->option("redirect$session");
  die "unknown redirect session $session\n" unless length($pref);
  $cgi = new CGI($pref);
}

&{$opt{'begin_callback'}}( $cgi, $fields, \%opt )
  if $opt{'begin_callback'};

my %qsearch = (
    'table'     => $table,
    'extra_sql' => ( $opt{'agent_virt'}
                       ? ' AND '. $curuser->agentnums_sql(
                                    'null_right' => $opt{'agent_null_right'}
                                  )
                       : ''
                   ),
);

my $mode;
my $object;
my $clone = '';
if ( $cgi->param('error') ) {

  $mode = 'error';

  $object = $class->new( {
    map { $_ => scalar($cgi->param($_)) } fields($table)
  });

  &{$opt{'error_callback'}}($cgi, $object, $fields, \%opt )
    if $opt{'error_callback'};

} elsif ( $cgi->param('clone') =~ /^(\d+)$/ ) {

  $mode = 'clone';

  $clone = $1;

  $qsearch{'extra_sql'} = ' AND '. $opt{'agent_clone_extra_sql'}
    if $opt{'agent_clone_extra_sql'};

  $object = qsearchs({ %qsearch, 'hashref' => { $pkey => $clone } });

  &{$opt{'clone_callback'}}($cgi, $object, $fields, \%opt )
    if $opt{'clone_callback'};

  #$object->$pkey('');

  $opt{action} ||= 'Add';

} elsif ( $cgi->keywords || $cgi->param($pkey) ) { #editing

  $mode = 'edit';

  my $value;
  if ( $cgi->param($pkey) ) {
    $value = $cgi->param($pkey)
  } else { 
    my( $query ) = $cgi->keywords;
    $value = $query;
  }
  $value =~ /^(\d+)$/ or die "unparsable $pkey";
  $object = qsearchs({ %qsearch, 'hashref' => { $pkey => $1 } })
    or die "$pkey $1 not found in $table";
  
  warn "$table $pkey => $1"
    if $opt{'debug'};

  &{$opt{'edit_callback'}}($cgi, $object, $fields)
    if $opt{'edit_callback'};

} else { #adding

  $mode = 'new';

  my $hashref = $opt{'new_hashref_callback'}
                  ? &{$opt{'new_hashref_callback'}}
                  : {};

  $object = $opt{'new_object_callback'}
              ? &{$opt{'new_object_callback'}}( $cgi, $hashref, $fields, \%opt )
              : $class->new( $hashref );

  &{$opt{'new_callback'}}($cgi, $object, $fields)
    if $opt{'new_callback'};

}

&{$opt{'end_callback'}}( $cgi, $object, $fields, \%opt )
  if $opt{'end_callback'};

$opt{action} ||= $object->$pkey() ? 'Edit' : 'Add';

my $title = $opt{action}. ' '. $opt{name};

my $viewall_url = $p . ( $opt{'viewall_dir'} || 'search' ) . "/$table.html";
$viewall_url = $opt{'viewall_url'} if $opt{'viewall_url'};  

my @menubar = ();
if ( $opt{'menubar'} ) {
  @menubar = @{ $opt{'menubar'} };
} else {
  my $items = $opt{'name'} ? $opt{'name'}.'s' : PL($opt{'name_singular'});
  @menubar = (
    "View all $items" => $viewall_url,
  );
}

</%init>