Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / httemplate / edit / elements / edit.html
index 272f950..c6d4553 100644 (file)
@@ -2,9 +2,13 @@
 
 Example:
 
-  include( 'elements/edit.html',  
-    'name'  =>
-    'table' =>
+  <& 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'         =>  #database table
+
     #? 'primary_key' => #required when the dbdef doesn't know...???
     'labels' => {
                   'column' => 'Label',
@@ -22,40 +26,48 @@ Example:
                                        #percentage
                                        #checkbox
                                        #select
-                                       #selectlayers (can't use after a tablebreak-tr-title yet... grep "OneTrueTable")
+                                       #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
-                                       #fixedhidden - hidden value from here
                                        #fixed-country
                                        #fixed-state
-                    'value' => 'Y', #for checkbox, title, fixed, fixedhidden
+                    'value' => 'Y', #for checkbox, title, fixed, hidden
                     'disabled' => 0,
                     'onchange' => 'javascript_function',
-                    'm2name_table'   => 'table_name',   #only tested w/
-                                                        # selectlayers so far
-                                                        # might work w/select
-                                                        # dunno others
-                    'm2name_namecol' => 'name_column',  # 
-                    'm2name_label'   => 'Label',        #
-                    'm2name_new_default' => \@table_name_objects, #default
-                                                                  #m2name
-                                                                  #objects for
-                                                                  #new records
-                    'm2name_error_callback' => sub { my($cgi, $object) = @_; },
-                    'm2name_remove_warnings' => \%warnings, #hashref of warning
-                                                            #messages for
-                                                            #m2name removal
-                    'm2name_new_js' => 'function_name', #javascript function
-                                                        #called on spawned rows
-                                                        #(one arg: new_element)
-                    'm2name_remove_js' => 'function_name', #js function called
-                                                           #when a row is
-                                                           #deleted
-                                                           #(three args:
-                                                           # value, text,
-                                                           #  'no_match')
+
+                    'include_opt_callback' => sub { my $object = @_;
+                                                    ( 'option' => 'value', );
+                                                  },
+
+                    '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
+                    #OR#
+                    'o2m_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',
@@ -83,78 +95,196 @@ Example:
     'menubar'     => '', #menubar arrayref
 
     #agent virtualization
-    'agent_virt'       => 1,
-    'agent_null_right' => 'Access Right Name',
-   
-    #run when re-displaying with an error
-    'error_callback' => sub { my( $cgi, $object, $fields_listref ) = @_; },
-   
-    #run when editing
-    'edit_callback' => sub { my( $cgi, $object, $fields_listref ) = @_; },
-   
-    # returns a hashref for the new object
-    'new_hashref_callback'
-   
-    #run when adding
-    'new_callback' => sub { my( $cgi, $object, $fields_listref ) = @_; },
-   
-    #XXX describe
-    'field_callback' => sub { },
+    'agent_virt'            => 1,
+    'agent_null'            => 1, #if true, always allow no-agentnum globals
+    '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', 
+
+    # optional link to delete this object; primary key will be appended
+    'delete_url' => $p.'misc/delete-something.html?',
+
+    #we're in a popup (no title/menu/searchboxes)
+    'popup' => 1,
+
+    #we're embedded (rows only: no header at all, no html_init, no error
+    # display, no <FORM>, no hidden fields for table name or primary key, no
+    # display of primary key, no submit button, no html_foot, no footer)
+    'embed' => $object, #need to pass the object
+    'tablenum' => 4, #need to specify a table number when using multiple
+                     #embedded edits on a page (and m2 stuff)
+
+    #don't show the primary key label and value
+    'no_pkey_display' => 1,
+
+    ###
+    # HTML callbacks
+    ###
+
+    'body_etc' => '', # Additional BODY attributes, i.e. onLoad=""
+
+    'html_init'   => '', #after the header/menubar
+
+    'form_init'   => '', #after html_init, error and the opening <FORM>, but
+                         #before any other form contents
+
+    'html_table_class' => '', #HTML <TABLE CLASS=
 
     #string or coderef of additional HTML to add before </TABLE>
     'html_table_bottom' => '',
-   
-    'viewall_dir' => '', #'search' or 'browse', defaults to 'search'
-   
+
+    #after </TABLE> but before the submit
     'html_bottom' => '', #string
     'html_bottom' => sub {
                            my $object = shift;
                            # ...
                            "html_string";
                          },
+    
+    #javascript function name, will be called with form name as arg
+    'onsubmit'   => 'check_form_data',
+
+    #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 ) = @_; },
+
+    #after the mode-specific object creation/search
+    'end_callback' = sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
+
+    ###mode-specific callbacks.  one (and only one) of these four is called
    
-    # overrides default popurl(1)."process/$table.html"
-    'post_url' => popurl(1).'process/something', 
+    #run when adding
+    'new_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
 
-    #we're in a popup (no title/menu/searchboxes)
-    'popup' => 1,
+    #run when editing
+    'edit_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
+
+    #run when re-displaying with an error
+    'error_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
    
-  );
+    #run when cloning
+    'clone_callback' => sub { my( $cgi, $object, $fields_listref, $opt_hashref ) = @_; },
 
-</%doc>
+    ###callbacks called in new mode only
+
+    # returns a hashref for the new object
+    'new_hashref_callback'
+
+    # returns the new object iself (otherwise, ->new is called)
+    'new_object_callback'
+
+    ###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>
+%
+% unless ( $opt{embed} ) {
+%
+%   my $title = $opt{action}. ' '. ( $opt{name} || $opt{'name_singular'} );
+%
+%   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,
+%     );
+%   }
+%
 <% include('/elements/header'. ( $opt{popup} ? '-popup' : '' ). '.html',
-              $title,
-              include( '/elements/menubar.html', @menubar )
-           )
+                $title,
+                include( '/elements/menubar.html', @menubar ),
+                $opt{'body_etc'},
+             )
 %>
 
-<% include('/elements/error.html') %>
+  <% 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">
+  <FORM NAME   = "edit_topform"
+        METHOD = POST
+        ACTION = "<% $url %>"
+        <% $opt{onsubmit} ? 'onSubmit="return '.$opt{onsubmit}.'(this)"' : '' %>
+  >
+
+  <INPUT TYPE="hidden" NAME="svcdb" VALUE="<% $table %>">
+  <INPUT TYPE="hidden" NAME="<% $pkey %>" VALUE="<% $clone ? '' : $object->$pkey() %>">
+
+  <% defined($opt{'form_init'}) 
+        ? ( ref($opt{'form_init'})
+              ? &{$opt{'form_init'}}()
+              : $opt{'form_init'}
+          )
+        : ''
+  %>
+
+%   unless ( $opt{'no_pkey_display'} ) {
+
+      <FONT SIZE="+1"><B>
+      <% ( $opt{labels} && exists $opt{labels}->{$pkey} )
+            ? $opt{labels}->{$pkey}
+            : $pkey
+      %>
+      </B></FONT>
+      #<% ( !$clone && $object->$pkey() ) || "(NEW)" %>
 
-<INPUT TYPE="hidden" NAME="svcdb" VALUE="<% $table %>">
-<INPUT TYPE="hidden" NAME="<% $pkey %>" VALUE="<% $object->$pkey() %>">
+%   }
 
-<FONT SIZE="+1"><B>
-<% ( $opt{labels} && exists $opt{labels}->{$pkey} )
-      ? $opt{labels}->{$pkey}
-      : $pkey
-%>
-</B></FONT>
-#<% $object->$pkey() || "(NEW)" %>
+% }
 
-%# <% ntable("#cccccc",0) %>
-<TABLE ID="OneTrueTable" BGCOLOR="#cccccc" BORDER=0 CELLSPACING=0>
+% my $tablenum = $opt{'tablenum'} || 0;
+<TABLE ID="TableNumber<% $tablenum++ %>"
+       <% $opt{html_table_class} ? 'CLASS="'. $opt{html_table_class}. '"'
+                                 : 'BGCOLOR="#cccccc" BORDER=0 CELLSPACING=0'
+       %>
+>
 
 % my $g_row = 0;
+% my @g_row_stack = ();
 % foreach my $f ( map { ref($_) ? $_ : {'field'=>$_} }
 %                       @$fields
 %                 ) {
 %
-%   &{ $opt{'field_callback'} }( $f )
+%   my $trash = &{ $opt{'field_callback'} }( $cgi, $object, $f )
 %     if $opt{'field_callback'};
 %
 %   my $field = $f->{'field'};
@@ -167,31 +297,102 @@ Example:
 %   my $onchange = $f->{'onchange'};
 %
 %   my $layer_values = {};
-%   if ( $f->{'layer_values_callback'} && ! $f->{'m2name_table'} ) {
-%     $layer_values = &{ $f->{'layer_values_callback'} }( $cgi, $object );
-%   }
+%   $layer_values = &{ $f->{'layer_values_callback'} }( $cgi, $object )
+%     if $f->{'layer_values_callback'}
+%     && ! $f->{'m2name_table'}
+%     && ! $f->{'o2m_table'}
+%     && ! $f->{'m2m_method'};
+%
 %   warn "layer values: ". Dumper($layer_values)
 %     if $opt{'debug'};
 %
 %   my %include_common = (
-%     #checkbox, title, fixed, fixedhidden
+%
+%     #text and derivitives
+%     'size'          => $f->{'size'},
+%     'maxlength'     => $f->{'maxlength'},
+%     'prefix'        => $f->{'prefix'},
+%     'postfix'       => $f->{'postfix'},
+%
+%     #textarea
+%     'rows'          => $f->{'rows'},
+%     'cols'          => $f->{'cols'},
+%
+%     #checkbox, title, fixed, hidden
 %     #& deprecated weird value hashref used only by reason.html
 %     'value'         => $f->{'value'},
 %
+%     #fixed
+%     'noescape'      => $f->{'noescape'},
+%
 %     #select(-*)
 %     'options'       => $f->{'options'},
 %     'labels'        => $f->{'labels'},
 %     'multiple'      => $f->{'multiple'},
+%     'label_showkey' => $f->{'label_showkey'},
 %     'disable_empty' => $f->{'disable_empty'},
 %     #select-reason
 %     'reason_class'  => $f->{'reason_class'},
+%     #select-agent
+%     'viewall_right' => $f->{'viewall_right'},
 %
 %     #selectlayers
 %     'layer_fields'  => $f->{'layer_fields'},
 %     'layer_values'  => $layer_values,
 %     'html_between'  => $f->{'html_between'},
+%
+%     #umm.  for select-agent_type at least
+%     'disabled'      => $f->{'disabled'},
+%     'fixed'         => $f->{'fixed'},
+%     'label_callback'=> $f->{'label_callback'},
+%     'element_etc'   => $f->{'element_etc'},
+%
+%     #for select-ticketing_queueid at least
+%     'post_options'  => $f->{'post_options'},
+%
+%     #any?
+%     'colspan'       => $f->{'colspan'},
+%     'required'      => $f->{'required'},
+%
+%     #contact
+%     'custnum'     => $f->{'custnum'},
+%     'prospectnum' => $f->{'prospectnum'},
 %   );
 %
+%   $include_common{$_} = $f->{$_} foreach grep exists($f->{$_}),
+%     qw( js_only html_only select_only layers_only cell_style ),#selectlayers,?
+%     qw( empty_label ),                                   # select-*
+%     qw( value_col compare_sub order_by ),                # select-table
+%     qw( table name_col ),                           #(select,checkboxes)-table
+%     qw( target_table link_table ),                       #checkboxes-table
+%     qw( hashref agent_virt agent_null agent_null_right ),#*-table
+%     qw( formatted_value ),                               #fixed
+%     qw( country ),                                       #select-country
+%     qw( width height config ),                           #htmlarea
+%     qw( alt_format ),                                    #select-cust_location
+%     qw( classnum ),                                   # select-inventory_item
+%     qw( aligned ),                                    # columnstart
+%   ;
+%
+%   #select-table
+%   $include_common{$_} = ref( $f->{$_} ) eq 'CODE'
+%                           ? &{ $f->{$_} }( $cgi, $object ) #, $f )
+%                           : $f->{$_}
+%     foreach grep exists($f->{$_}), qw( extra_sql );
+%
+%   if ( $type eq 'tablebreak-tr-title' ) {
+%     $include_common{'table_id'} = 'TableNumber'. $tablenum++;
+%   }
+%   if ( $type eq 'tablebreak-tr-title' || $type eq 'title' ) {
+%     $include_common{'colspan'} = $f->{colspan} if $f->{colspan};
+%   }
+%
+%   if ( $f->{include_opt_callback} ) {
+%     %include_common = ( %include_common,
+%                         &{ $f->{include_opt_callback} }( $object )
+%                       );
+%   }
+%
 %   my $layer_prefix_on = '';
 %
 %   my $include_sub = sub {
@@ -201,7 +402,7 @@ Example:
 %
 %     my $include = $type;
 %     $include = "input-$include" if $include =~ /^(text|money|percentage)$/;
-%     $include = "tr-$include" unless $include =~ /^(hidden|tablebreak)/;
+%     $include = "tr-$include" unless $include =~ /^(hidden|tablebreak|column)/;
 %
 %     $include_common{'layer_prefix'} = "$field$fieldnum."
 %       if $layer_prefix_on;
@@ -214,36 +415,96 @@ Example:
 %         %include_common,
 %         %opt,
 %     );
+%
+%     if ( $include eq 'tr-input-date-field' ) {
+%      # it's either hacking it here, or changing a lot more stuff
+%      @include = (
+%              "/elements/$include.html", {
+%                      'name' => $field,
+%                      'value' => $opt{curr_value},
+%                      'label' => $label,
+%                      'noinit' => $f->{noinit},
+%           'required' => $f->{'required'},
+%              }
+%      );
+%     }
+%
 %     @include;
 %   };
 %
-%   $g_row++;
-%   $g_row++ if $type eq 'title';
+%   my $column_sub = sub {
+%     my %opt = @_;
+%
+%     my $column   = delete($opt{field});
+%     my $fieldnum = delete($opt{fieldnum});
+%     my $include  = delete($opt{type}) || 'text';
+%     $include = "input-$include" if $include =~ /^(text|money|percentage)$/;
+%
+%     ( "/elements/$include.html",
+%         'field'        => $field.'__'.$column.$fieldnum,
+%         'id'           => $field.'__'.$column.$fieldnum,
+%         'layer_prefix' => $field.'__'.$column.$fieldnum.".",
+%         ( $fieldnum
+%             ? ('cell_style' => 'border-top:1px solid black')
+%             : ()
+%         ),
+%         'cgi' => $cgi,
+%         %opt,
+%     );
+%   };
+%
+%   unless ( $type =~ /^column/ ) {
+%     $g_row = 1 if $type eq 'tablebreak-tr-title';
+%     $g_row++;
+%     $g_row++ if $type eq 'title';
+%     $g_row += scalar( @{ $f->{options} } )-1 if $type eq 'radio';
+%   } 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'} ) { #XXX test this for all types of fields
-%     my $table = $f->{'m2name_table'};
-%     my $col   = $f->{'m2name_namecol'};
+%   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
+%
+%     my($table, $col);
+%     if ( $f->{'m2name_table'} ) {
+%       $table = $f->{'m2name_table'};
+%       $col   = $f->{'m2name_namecol'};
+%     } elsif ( $f->{'o2m_table'} ) {
+%       $table = $f->{'o2m_table'};
+%       $col   = dbdef->table($f->{'o2m_table'})->primary_key;
+%     } 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 m2names
+%     #print out the fields for the existing m2s
 %     my @existing = ();
 %     if ( $mode eq 'error' ) {
-%       @existing = &{ $f->{'m2name_error_callback'} }( $cgi, $object );
-%     } elsif ( $object->$pkey() ) { # $mode eq 'edit'
+%       @existing = &{ $f->{'m2_error_callback'} }( $cgi, $object );
+%     } elsif ( $object->$pkey() ) { # $mode eq 'edit'||'clone'
 %       @existing = $object->$table();
-%     } elsif ( $f->{'m2name_new_default'} ) { # && $mode eq 'new'
-%       @existing = @{ $f->{'m2name_new_default'} };
+%       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->{'m2name_label'}).
+%                      lc($f->{'m2_label'}).
 %                      qq(" onClick="remove_$field($fieldnum);").
 %                      ' STYLE="color:#ff0000;font-weight:bold;'.
 %                              'padding-left:2px;padding-right:2px"'.
-%                      '>&nbsp;'. ($f->{'m2name_label'} || $field ). ' ';
+%                      '>&nbsp;'. ($f->{'m2_label'} || $field ). ' ';
 %       
 %       if ( $f->{'layer_values_callback'} ) {
 %         my %switches = ( 'mode' => $mode );
@@ -252,7 +513,7 @@ Example:
 %       }
 %       warn "layer values: ". Dumper($layer_values)
 %         if $opt{'debug'};
-%
+%      
 %       my @existing = &{ $include_sub }(
 %         'label'        => $ex_label,
 %         'fieldnum'     => $fieldnum,
@@ -261,8 +522,35 @@ Example:
 %         'layer_values' => $layer_values,
 %         'cell_style'   => ( $fieldnum ? 'border-top:1px solid black' : '' ),
 %       );
+%       $existing[0] =~ s(^/elements/tr-)(/elements/);
+%       my @label = @existing;
+%       $label[0] = '/elements/tr-td-label.html';
 
+        <% include( @label ) %>
+        <TD COLSPAN="<% $f->{'colspan'} || 1 %>">
         <% include( @existing ) %>
+        </TD>
+
+%       if ( $f->{'m2_fields'} ) {
+%         foreach my $c ( @{ $f->{'m2_fields'} } ) {
+%           my $column = $c->{field};
+%           my @column = &{ $column_sub }( %$c,
+%                                          'fieldnum' => $fieldnum,
+%                                          'curr_value' => $name_obj->$column()
+%                                        );
+
+            <TD id='<% $field %>__<% $column %>_label<% $fieldnum %>'
+                style='text-align:right;vertical-align:top;
+                       border-top:1px solid black;padding-top:5px;'>
+              <% $c->{'label'} || '' %>
+            </TD>
+            <TD style='border-top:1px solid black;padding-top:3px;'>
+              <% include( @column ) %>
+            </TD>
+%         }
+%       }
+
+        </TR>
 
 %       $fieldnum++;
 %       $g_row++;
@@ -270,7 +558,13 @@ Example:
 %     #$field .= $fieldnum;
 %     $onchange .= "\nspawn_$field(what);";
 %   } else {
-%     $curr_value = $object->$field();
+%     if ( $f->{curr_value_callback} ) {
+%       $curr_value = &{ $f->{curr_value_callback} }( $cgi, $object, $field ),
+%     } else {
+%       $curr_value = $object->$field() if $field;
+%     }
+%     $curr_value = &{ $opt{'value_callback'} }( $f->{'field'}, $curr_value )
+%       if $opt{'value_callback'} && $mode ne 'error';
 %   }
 %
 %   my @include = &{ $include_sub }(
@@ -278,59 +572,94 @@ Example:
 %     'fieldnum'   => $fieldnum,
 %     'curr_value' => $curr_value,
 %     'object'     => $object,
+%     'cgi'        => $cgi,
 %     'onchange'   => $onchange,
-%     'cell_style'   => ( $fieldnum ? 'border-top:1px solid black' : '' ),
+%     ( $fieldnum ? ('cell_style' => 'border-top:1px solid black') : () ),
 %   );
+%
+%   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
+%     $include[0] =~ s(^/elements/tr-)(/elements/);
+%     my @label = @include;
+%     $label[0] = '/elements/tr-td-label.html';
+
+      <% include( @label ) %>
+      <TD COLSPAN="<% $f->{'colspan'} || 1 %>">
+      <% include( @include ) %>
+      </TD>
+
+%     if ( $f->{'m2_fields'} ) {
+%       foreach my $c ( @{ $f->{'m2_fields'} } ) {
+%         my $column = $c->{field};
+%         my @column = &{ $column_sub }( %$c, 'fieldnum' => $fieldnum );
+
+          <TD id='<% $field %>__<% $column %>_label<% $fieldnum %>'
+              style='text-align:right;vertical-align:top;
+                     border-top:1px solid black;padding-top:5px;'>
+            <% $c->{'label'} || '' %>
+          </TD>
+          <TD style='border-top:1px solid black;padding-top:3px;'>
+            <% include( @column ) %>
+          </TD>
+%       }
+%     }
 
-    <% include( @include ) %>
+      </TR>
+
+%   } else {
 
-%   if ( $f->{'m2name_table'} ) {
+      <% include( @include ) %>
+
+%   }
+%   if ( $f->{'m2name_table'} || $f->{'o2m_table'} || $f->{'m2m_method'} ) {
 
       <SCRIPT TYPE="text/javascript">
 
-        var rownum = <% $g_row %>;
-        var fieldnum = <% $fieldnum %>;
+        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 field_regex = /(\d+)(_[a-z_]+)?$/;
           var match = field_regex.exec(what.name);
           if ( !match ) {
-            alert(what.name + " didn't match?!");
+            alert(what.name + " didn't match for " + what);
             return;
           }
-          if ( match[1] != fieldnum ) {
+          if ( match[1] != <%$field%>_fieldnum ) {
             return;
           }
 
           // change the label on the last entry & add a remove button
-          var prev_label = document.getElementById('<% $field %>_label' + fieldnum );
-          prev_label.innerHTML = '<INPUT TYPE="button" VALUE="X" TITLE="Remove this <% lc($f->{'m2name_label'}) %>" onClick="remove_<% $field %>(' + fieldnum + ');" STYLE="color:#ff0000;font-weight:bold;padding-left:2px;padding-right:2px" >&nbsp;<% $f->{'m2name_label'} || $field %>';
+          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 %>';
 
-          fieldnum++;
+          <%$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 %>;
+%         #until the rest have html/js_only
+%         if ( $type eq 'selectlayers' || $type =~ /^select-cgp_rule_/ ) {
+            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, fieldnum );
-          newfunc = newfunc.replace( magic_regex, fieldnum );
+          newrow  = newrow.replace(  magic_regex, <%$field%>_fieldnum );
+          newfunc = newfunc.replace( magic_regex, <%$field%>_fieldnum );
 
           // evaluate new_func
           if (window.ActiveXObject) {
@@ -343,13 +672,13 @@ Example:
           // add new row
 
           //hmm, can't use selectlayers after a tablebreak-title for now
-          var table = document.getElementById('OneTrueTable');
+          var table = document.getElementById('TableNumber<% $tablenum-1 %>');
 
-          var row = table.insertRow(rownum++);
+          var row = table.insertRow(<%$field%>_rownum++);
 
           var label_cell = document.createElement('TD');
 
-          label_cell.id = '<% $field %>_label' + fieldnum;
+          label_cell.id = '<% $field %>_label' + <%$field%>_fieldnum;
 
           label_cell.style.textAlign = "right";
           label_cell.style.verticalAlign = "top";
@@ -364,15 +693,49 @@ Example:
 
           widget_cell.style.borderTop = "1px solid black";
           widget_cell.style.paddingTop = "3px";
+          widget_cell.colSpan = "<% $f->{'colspan'} || 1 %>";
 
           widget_cell.innerHTML = newrow;
 
           row.appendChild(widget_cell);
 
-%         if ( $f->{'m2name_new_js'} ) {
+%         if ( $f->{'m2_fields'} ) {
+%           foreach my $c ( @{ $f->{'m2_fields'} } ) {
+%             my $column = $c->{field};
+%             my @column = &{ $column_sub }(%$c, 'fieldnum' => 'MAGIC_NUMBER');
+
+              var column =  <% include(@column, html_only=>1) |js_string %>;
+              column  = column.replace(  magic_regex, <%$field%>_fieldnum );
+
+              var column_label = document.createElement('TD');
+              column_label.id =
+                '<% $field %>__<% $column %>_label' + <%$field%>_fieldnum;
+
+              column_label.style.textAlign = "right";
+              column_label.style.verticalAlign = "top";
+              column_label.style.borderTop = "1px solid black";
+              column_label.style.paddingTop = "5px";
+
+              column_label.innerHTML = '<% $c->{'label'} || '' %>';
+
+              row.appendChild(column_label);
+          
+              var column_widget = document.createElement('TD');
+
+              column_widget.style.borderTop = "1px solid black";
+              column_widget.style.paddingTop = "3px";
+
+              column_widget.innerHTML = column;
+
+              row.appendChild(column_widget);
+
+%           }
+%         }
+
+%         if ( $f->{'m2_new_js'} ) {
             // take out items selected in previous dropdowns
-            var new_element = document.getElementById("<%$field%>" + fieldnum );
-            <% $f->{'m2name_new_js'} %>(new_element);
+            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
@@ -386,7 +749,12 @@ Example:
           //alert("remove <%$field%> " + remove_fieldnum);
           var select = document.getElementById('<%$field%>' + remove_fieldnum);
 
-%         my $warnings = $f->{'m2name_remove_warnings'};
+          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 ) {
@@ -402,9 +770,9 @@ Example:
           var label_td = document.getElementById('<%$field%>_label' + remove_fieldnum );
           label_td.parentNode.style.display = 'none';
 
-%         if ( $f->{m2name_remove_js} ) {
+%         if ( $f->{m2_remove_js} ) {
             var opt = select.options[select.selectedIndex];
-            <% $f->{m2name_remove_js} %>( opt.value, opt.text, 'no_match');
+            <% $f->{m2_remove_js} %>( opt.value, opt.text, 'no_match');
 %         }
 
         }
@@ -427,13 +795,47 @@ Example:
       : $opt{'html_bottom'}
 %>
 
-<BR>
+% unless ($opt{'embed'}) {
+
+  <BR>
+
+%   unless ($opt{'no_submit'}) {
+      <INPUT TYPE     = "submit"
+             ID       = "submit"
+             VALUE    = "<% ( !$clone && $object->$pkey() )
+                              ? "Apply changes"
+                              : "Add ". ($opt{'name'} || $opt{'name_singular'})
+                         %>"
+      >
+%     if ( $opt{'delete_url'} and $object->get($pkey) ) {
+%       my $delete_msg = 'Delete this '.
+%          ($opt{'name_singular'} || $opt{'name'});
+%       my $delete_url = $opt{'delete_url'};
+%       $delete_url .= '?' unless $delete_url =~ /\?/;
+%       $delete_url .= $object->get($pkey);
+        <SCRIPT TYPE="text/javascript">
+        function confirm_delete() {
+          if(confirm(<% $delete_msg . '?' |js_string %>)) {
+            window.location.href = <% $delete_url |js_string %>;
+          }
+        }
+        </SCRIPT>
+        <INPUT TYPE     = "button"
+               VALUE    = "<% $delete_msg |h %>"
+               onclick  = "confirm_delete()">
+%     }
+%   }
+
+  </FORM>
 
-<INPUT TYPE="submit" ID="submit" VALUE="<% $object->$pkey() ? "Apply changes" : "Add $opt{'name'}" %>">
+  <% ref( $opt{'html_foot'} )
+        ? &{ $opt{'html_foot'} }( $object )
+        : $opt{'html_foot'}
+  %>
 
-</FORM>
+  <% include("/elements/footer.html") %>
 
-<% include("/elements/footer.html") %>
+% }
 <%init>
 
 my(%opt) = @_;
@@ -449,85 +851,113 @@ my $fields = $opt{'fields'}
              || [ 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);
-}
+my( $mode, $object);
+my $clone = '';
+if ( $opt{'embed'} ) {
 
-my $object;
-my $mode;
-if ( $cgi->param('error') ) {
+  $object = $opt{'embed'};
+  $mode = $cgi->param('error')
+            ? 'error'
+            : $object->$pkey()
+              ? 'edit'
+              : 'new';
 
-  $mode = 'error';
+} else {
 
+  #$m->comp('/elements/handle_uri_query');
+  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);
+  }
 
-  $object = $class->new( {
-    map { $_ => scalar($cgi->param($_)) } fields($table)
-  });
+  &{$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'}
+                                    )
+                         : ''
+                     ),
+  );
 
-  &{$opt{'error_callback'}}($cgi, $object, $fields)
-    if $opt{'error_callback'};
+  if ( $cgi->param('error') ) {
 
-} elsif ( $cgi->keywords || $cgi->param($pkey) ) { #editing
+    $mode = 'error';
 
-  $mode = 'edit';
+    $object = $class->new( {
+      map { $_ => scalar($cgi->param($_)) } fields($table)
+    });
 
-  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({
-    'table'     => $table,
-    'hashref'   => { $pkey => $1 },
-    'extra_sql' => ( $opt{'agent_virt'}
-                       ? ' AND '. $curuser->agentnums_sql(
-                                    'null_right' => $opt{'agent_null_right'}
-                                  )
-                       : ''
-                   ),
-  });
-  warn "$table $pkey => $1"
-    if $opt{'debug'};
+    &{$opt{'error_callback'}}( $cgi, $object, $fields, \%opt )
+      if $opt{'error_callback'};
 
-  &{$opt{'edit_callback'}}($cgi, $object, $fields)
-    if $opt{'edit_callback'};
+  } elsif ( $cgi->param('clone') =~ /^(\d+)$/ ) {
 
-} else { #adding
+    $mode = 'clone';
 
-  $mode = 'new';
+    $clone = $1;
 
-  my $hashref = $opt{'new_hashref_callback'}
-                  ? &{$opt{'new_hashref_callback'}}
-                  : {};
+    $qsearch{'extra_sql'} = ' AND '. $opt{'agent_clone_extra_sql'}
+      if $opt{'agent_clone_extra_sql'};
 
-  $object = $class->new( $hashref );
+    $object = qsearchs({ %qsearch, 'hashref' => { $pkey => $clone } })
+      or die "$pkey $clone not found in $table";
 
-  &{$opt{'new_callback'}}($cgi, $object, $fields)
-    if $opt{'new_callback'};
+    &{$opt{'clone_callback'}}( $cgi, $object, $fields, \%opt )
+      if $opt{'clone_callback'};
 
-}
+    #$object->$pkey('');
 
-my $action = $object->$pkey() ? 'Edit' : 'Add';
+    $opt{action} ||= 'Add';
 
-my $title = "$action $opt{'name'}";
+  } elsif ( $cgi->keywords || $cgi->param($pkey) ) { #editing
 
-my $viewall_url = $p . ( $opt{'viewall_dir'} || 'search' ) . "/$table.html";
-$viewall_url = $opt{'viewall_url'} if $opt{'viewall_url'};  
+    $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, \%opt )
+      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, \%opt )
+      if $opt{'new_callback'};
+
+  }
+
+  &{$opt{'end_callback'}}( $cgi, $object, $fields, \%opt )
+    if $opt{'end_callback'};
+
+  $opt{action} ||= $object->$pkey() ? 'Edit' : 'Add';
 
-my @menubar = ();
-if ( $opt{'menubar'} ) {
-  @menubar = @{ $opt{'menubar'} };
-} else {
-  @menubar = (
-    #eventually use Lingua::bs to pluralize
-    "View all $opt{'name'}s" => $viewall_url,
-  );
 }
 
 </%init>