Browse Source

Merge branch '6.x-1.x' of git.drupal.org:sandbox/spficklin/1337878 into 6.x-1.x

spficklin 12 years ago
parent
commit
becb95f626

+ 5 - 5
tripal_analysis/tripal_analysis.views.inc

@@ -35,10 +35,10 @@ function tripal_analysis_views_data()  {
   if (module_exists('tripal_views')) {
   if (module_exists('tripal_views')) {
     // Base Table: Analysis
     // Base Table: Analysis
     $tablename = 'analysis';
     $tablename = 'analysis';
-    // get the setup with the lightest priority. That's the table 
+    // get the setup with the lightest priority. That's the table
     // that currently integrated with views.
     // that currently integrated with views.
-    $priority = tripal_views_get_table_lightest_priority($tablename);
-      
+    $priority = 9;
+
     // check to see if the table is integrated. If it is then integrate it's
     // check to see if the table is integrated. If it is then integrate it's
     // corresponding 'chado_[table]' table.
     // corresponding 'chado_[table]' table.
     if (!tripal_views_is_integrated($tablename, $priority)) {
     if (!tripal_views_is_integrated($tablename, $priority)) {
@@ -66,7 +66,7 @@ function tripal_analysis_views_data()  {
       'analysisprop'
       'analysisprop'
     );
     );
     foreach ($tables as $tablename) {
     foreach ($tables as $tablename) {
-      $priority = tripal_views_get_table_lightest_priority($tablename);     
+      $priority = 9;
       if (!tripal_views_is_integrated($tablename, $priority)) {
       if (!tripal_views_is_integrated($tablename, $priority)) {
         $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE, $priority);
         $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE, $priority);
         tripal_views_integration_add_entry($table_integration_array);
         tripal_views_integration_add_entry($table_integration_array);
@@ -311,7 +311,7 @@ function tripal_analysis_views_default_views() {
     ),
     ),
     'program' => array(
     'program' => array(
       'operator' => '=',
       'operator' => '=',
-      'value' => array(),
+      'value' => '',
       'group' => '0',
       'group' => '0',
       'exposed' => TRUE,
       'exposed' => TRUE,
       'expose' => array(
       'expose' => array(

+ 202 - 107
tripal_bulk_loader/tripal_bulk_loader.admin.templates.inc

@@ -90,8 +90,8 @@ function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode)
   $form['records']['description'] = array(
   $form['records']['description'] = array(
     '#type' => 'item',
     '#type' => 'item',
     '#value' => 'Records will be inserted into the chado database in the order listed below. To '
     '#value' => 'Records will be inserted into the chado database in the order listed below. To '
-      .'change this order: <ul><li>Drag the rows into the correct order OR</li><li>Enter '
-      .'the numbers 1 and up in the Order textboxes to indicate the correct order.</li></ul>',
+      .'change this order: <ul><li>Drag the rows into the correct order <br/>(If you don\'t have javascript enabled then enter '
+      .'the numbers 1 and up in the Order textboxes to indicate the correct order).</li></ul>',
   );
   );
 
 
   $form['records']['records-data'] = array(
   $form['records']['records-data'] = array(
@@ -137,46 +137,46 @@ function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode)
         $mode_value = '';
         $mode_value = '';
         if ($table_array['optional']) {
         if ($table_array['optional']) {
           $mode_value .= 'optional ';
           $mode_value .= 'optional ';
-        } 
+        }
 
 
         // for backwards compatibility we want to convert insert_unique to be 'insert'
         // for backwards compatibility we want to convert insert_unique to be 'insert'
         // and optional to 'insert'
         // and optional to 'insert'
         if (strcmp($table_array['mode'], 'insert_unique')==0) {
         if (strcmp($table_array['mode'], 'insert_unique')==0) {
           $mode_value .= 'insert or select if duplicate';
           $mode_value .= 'insert or select if duplicate';
-        } 
+        }
         elseif (strcmp($table_array['mode'], 'optional')==0) {
         elseif (strcmp($table_array['mode'], 'optional')==0) {
           $mode_value .= 'optional insert';
           $mode_value .= 'optional insert';
-        } 
+        }
         elseif (strcmp($table_array['mode'], 'insert_once')==0) {
         elseif (strcmp($table_array['mode'], 'insert_once')==0) {
           $mode_value .= 'insert once';
           $mode_value .= 'insert once';
-        } 
+        }
          elseif (strcmp($table_array['mode'], 'select_once')==0) {
          elseif (strcmp($table_array['mode'], 'select_once')==0) {
           $mode_value .= 'select once';
           $mode_value .= 'select once';
-        } 
+        }
         elseif ($table_array['mode']) {
         elseif ($table_array['mode']) {
           $mode_value .= $table_array['mode'];
           $mode_value .= $table_array['mode'];
         }
         }
         else {
         else {
           $mode_value .= 'insert';
           $mode_value .= 'insert';
         }
         }
-        
-        // add in the select if duplicate 
+
+        // add in the select if duplicate
         if ($table_array['select_if_duplicate']) {
         if ($table_array['select_if_duplicate']) {
           $mode_value .= ' or select if duplicate';
           $mode_value .= ' or select if duplicate';
-        } 
+        }
         if ($table_array['select_optional']) {
         if ($table_array['select_optional']) {
           $mode_value .= ' (no fail)';
           $mode_value .= ' (no fail)';
         }
         }
         if ($table_array['update_if_duplicate']) {
         if ($table_array['update_if_duplicate']) {
           $mode_value .= ' or update if duplicate';
           $mode_value .= ' or update if duplicate';
-        } 
-        
-        
+        }
+
+
         // add in the disabled
         // add in the disabled
         if ($table_array['disable']) {
         if ($table_array['disable']) {
           $mode_value .= '. <font color="Red">DISABLED</font>';
           $mode_value .= '. <font color="Red">DISABLED</font>';
-        } 
-        
+        }
+
         $form['records']['records-data'][$priority] = array(
         $form['records']['records-data'][$priority] = array(
           'title' => array(
           'title' => array(
             '#type' => 'markup',
             '#type' => 'markup',
@@ -207,17 +207,17 @@ function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode)
           ),
           ),
           'submit-edit_record' => array(
           'submit-edit_record' => array(
             '#type' => 'submit',
             '#type' => 'submit',
-            '#name' => (string)$priority,
+            '#name' => ($priority !== 0) ? (string)$priority : 'zero',
             '#value' => 'Edit Record',
             '#value' => 'Edit Record',
           ),
           ),
           'submit-add_field' => array(
           'submit-add_field' => array(
             '#type' => 'submit',
             '#type' => 'submit',
-            '#name' => (string)$priority,
+            '#name' => ($priority !== 0) ? (string)$priority : 'zero',
             '#value' => 'Add Field',
             '#value' => 'Add Field',
           ),
           ),
           'submit-duplicate_record' => array(
           'submit-duplicate_record' => array(
             '#type' => 'submit',
             '#type' => 'submit',
-            '#name' => (string)$priority,
+            '#name' => ($priority !== 0) ? (string)$priority : 'zero',
             '#value' => 'Duplicate Record'
             '#value' => 'Duplicate Record'
           ),
           ),
         );
         );
@@ -230,25 +230,25 @@ function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode)
             }
             }
             else {
             else {
               // for backwards compatibility we need to get the FK relationship to find
               // for backwards compatibility we need to get the FK relationship to find
-              // out what field we're joining on.  For templates created using a 
-              // previous version this information isn't stored in the template 
+              // out what field we're joining on.  For templates created using a
+              // previous version this information isn't stored in the template
               // so we need to get it.
               // so we need to get it.
               $fk_priority = $form_state['storage']['record2priority'][$field['foreign key']];
               $fk_priority = $form_state['storage']['record2priority'][$field['foreign key']];
-              $fk_table = $form_state['storage']['template'][$fk_priority]['table'];    
+              $fk_table = $form_state['storage']['template'][$fk_priority]['table'];
               $tbl_description = tripal_core_get_chado_table_schema($table_array['table']);
               $tbl_description = tripal_core_get_chado_table_schema($table_array['table']);
               foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
               foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
                 foreach ($key_array['columns'] as $left_field => $right_field) {
                 foreach ($key_array['columns'] as $left_field => $right_field) {
-                  if ($key_table == $fk_table and $left_field == $field['field']) {                  
+                  if ($key_table == $fk_table and $left_field == $field['field']) {
                     $fk_value = $field['foreign key'] . " ($right_field)";
                     $fk_value = $field['foreign key'] . " ($right_field)";
                   }
                   }
                 }
                 }
               }
               }
-            }            
+            }
           }
           }
 
 
           $form['fields']['fields-data'][$i] = array(
           $form['fields']['fields-data'][$i] = array(
             'record_id' => array(
             'record_id' => array(
-              '#type' => 'item',              
+              '#type' => 'item',
               '#value' =>  $table_array['record_id'],
               '#value' =>  $table_array['record_id'],
               '#prefix' => "<a name=\"fields_$priority\"></a>",
               '#prefix' => "<a name=\"fields_$priority\"></a>",
               '#suffix' => "<p><a href=\"#record_$priority\"> View Record </a></p>",
               '#suffix' => "<p><a href=\"#record_$priority\"> View Record </a></p>",
@@ -353,6 +353,12 @@ function tripal_bulk_loader_modify_template_base_form_submit($form, &$form_state
   }
   }
 
 
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+
+  // part of fix for 1st button set not working on records list (edit record, duplicate record, add field)
+  if ($form_state['clicked_button']['#name'] === 'zero') {
+    $form_state['clicked_button']['#name'] = '0';
+  }
+
   switch ($op) {
   switch ($op) {
     // Initialize after template is chosen ----------------------------------------
     // Initialize after template is chosen ----------------------------------------
     case 'Edit Template':
     case 'Edit Template':
@@ -572,7 +578,7 @@ function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mod
       '#options'       => $templates,
       '#options'       => $templates,
       '#default_value' => $form_state['storage']['template_id'],
       '#default_value' => $form_state['storage']['template_id'],
       '#weight'        => 0,
       '#weight'        => 0,
-      '#required'      => TRUE,     
+      '#required'      => TRUE,
     );
     );
   }
   }
 
 
@@ -583,9 +589,9 @@ function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mod
     '#description' => t('Use this serialized array for import.'),
     '#description' => t('Use this serialized array for import.'),
     '#rows' => 15,
     '#rows' => 15,
     '#weight' => 5,
     '#weight' => 5,
-  
+
   );
   );
-  
+
   $form['submit'] = array(
   $form['submit'] = array(
     '#type' => 'submit',
     '#type' => 'submit',
     '#value' => 'Submit',
     '#value' => 'Submit',
@@ -612,9 +618,9 @@ function tripal_bulk_loader_import_export_template_form_submit($form, &$form_sta
       $t = preg_replace("/\n\s+array/", "array", $t); // move array( to previous line
       $t = preg_replace("/\n\s+array/", "array", $t); // move array( to previous line
       $t = preg_replace("/true/", "TRUE", $t); // upper case true
       $t = preg_replace("/true/", "TRUE", $t); // upper case true
       $t = preg_replace("/false/", "FALSE", $t); // upper case false
       $t = preg_replace("/false/", "FALSE", $t); // upper case false
-      $t = preg_replace("/array\(/", "array (", $t); // put a space between array and paren      
-    
-      $form_state['storage']['template_array'] = $t; 
+      $t = preg_replace("/array\(/", "array (", $t); // put a space between array and paren
+
+      $form_state['storage']['template_array'] = $t;
       $form_state['storage']['template_id'] = $form_state['values']['template_id'];
       $form_state['storage']['template_id'] = $form_state['values']['template_id'];
     break;
     break;
     case 'import':
     case 'import':
@@ -700,37 +706,37 @@ function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
   else {
   else {
     $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
     $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
   }
   }
-  
+
   // get the default mode
   // get the default mode
   $mode = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['mode'];
   $mode = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['mode'];
   if (!$mode) {
   if (!$mode) {
      $mode = 'insert';
      $mode = 'insert';
   }
   }
-  
+
   // get default for the select optional
   // get default for the select optional
   $select_optional = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['select_optional'];
   $select_optional = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['select_optional'];
   if (!isset($select_optional)) {
   if (!isset($select_optional)) {
     $select_optional = 0;
     $select_optional = 0;
   }
   }
-  
+
   // get default for the select if duplicate
   // get default for the select if duplicate
   $select_if_duplicate = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['select_if_duplicate'];
   $select_if_duplicate = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['select_if_duplicate'];
   if (!isset($select_if_duplicate)) {
   if (!isset($select_if_duplicate)) {
     $select_if_duplicate = 1;
     $select_if_duplicate = 1;
   }
   }
-  
+
   // get default for the update if duplicate
   // get default for the update if duplicate
   $update_if_duplicate = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['update_if_duplicate'];
   $update_if_duplicate = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['update_if_duplicate'];
   if (!isset($update_if_duplicate)) {
   if (!isset($update_if_duplicate)) {
     $update_if_duplicate = 0;
     $update_if_duplicate = 0;
   }
   }
-  
+
   // get default for the select if duplicate
   // get default for the select if duplicate
   $optional = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['optional'];
   $optional = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['optional'];
   if (!isset($optional)) {
   if (!isset($optional)) {
     $optional = 0;
     $optional = 0;
   }
   }
-  
+
   // get the default for disabling the record
   // get the default for disabling the record
   $disable = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['disable'];
   $disable = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['disable'];
 
 
@@ -739,7 +745,7 @@ function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
      $mode = 'insert';
      $mode = 'insert';
      $select_if_duplicate = 1;
      $select_if_duplicate = 1;
   }
   }
-  
+
   // this is just for backwards compatibility. the insert_unique mode type is no longer available
   // this is just for backwards compatibility. the insert_unique mode type is no longer available
   if (strcmp($mode, 'optional')==0) {
   if (strcmp($mode, 'optional')==0) {
      $mode = 'insert';
      $mode = 'insert';
@@ -800,13 +806,13 @@ function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
     '#title' => 'Action to take when Loading Record',
     '#title' => 'Action to take when Loading Record',
     '#options' => array(
     '#options' => array(
       'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
       'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
-      'select_once' => 'SELECT ONCE: Select the record only once for the entire file.',  
+      'select_once' => 'SELECT ONCE: Select the record only once for the entire file.',
       'insert' => 'INSERT: Insert the record',
       'insert' => 'INSERT: Insert the record',
       'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire file',
       'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire file',
     ),
     ),
     '#default_value' => $mode
     '#default_value' => $mode
   );
   );
-  
+
   $form['edit_record']['select_options'] = array(
   $form['edit_record']['select_options'] = array(
      '#type' => 'markup',
      '#type' => 'markup',
      '#value' => t('Additional Select Options:'),
      '#value' => t('Additional Select Options:'),
@@ -817,35 +823,35 @@ function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
      '#description' => t('By default if a select does not find a match the loader will fail, or if it finds too many matches it will fail.  Check here to allow the loader to continue when no match is found. In either case no value is passed on.'),
      '#description' => t('By default if a select does not find a match the loader will fail, or if it finds too many matches it will fail.  Check here to allow the loader to continue when no match is found. In either case no value is passed on.'),
      '#default_value' => $select_optional
      '#default_value' => $select_optional
   );
   );
-  
+
   $form['edit_record']['insert_options'] = array(
   $form['edit_record']['insert_options'] = array(
      '#type' => 'markup',
      '#type' => 'markup',
      '#prefix' => '<br>',
      '#prefix' => '<br>',
      '#value' => t('Additional Insert Options:'),
      '#value' => t('Additional Insert Options:'),
   );
   );
-    
+
   $form['edit_record']['select_if_duplicate'] = array(
   $form['edit_record']['select_if_duplicate'] = array(
      '#type' => 'checkbox',
      '#type' => 'checkbox',
      '#title' => t('SELECT if duplicate (no insert)'),
      '#title' => t('SELECT if duplicate (no insert)'),
      '#description' => t('If this is not the first time this record has been added then perform a select rather than an insert.'),
      '#description' => t('If this is not the first time this record has been added then perform a select rather than an insert.'),
      '#default_value' => $select_if_duplicate
      '#default_value' => $select_if_duplicate
   );
   );
-  
-  
-// TODO: finish coding up the update_if_duplicate functionality  
+
+
+// TODO: finish coding up the update_if_duplicate functionality
   $form['edit_record']['update_if_duplicate'] = array(
   $form['edit_record']['update_if_duplicate'] = array(
      '#type' => 'checkbox',
      '#type' => 'checkbox',
      '#title' => t('UPDATE if duplicate (no insert)'),
      '#title' => t('UPDATE if duplicate (no insert)'),
      '#description' => t('If this is not the first time this record has been added then perform an update rather than an insert.'),
      '#description' => t('If this is not the first time this record has been added then perform an update rather than an insert.'),
      '#default_value' => $update_if_duplicate
      '#default_value' => $update_if_duplicate
-  );  
-  
+  );
+
   $form['edit_record']['optional'] = array(
   $form['edit_record']['optional'] = array(
      '#type' => 'checkbox',
      '#type' => 'checkbox',
      '#title' => t('Optional'),
      '#title' => t('Optional'),
      '#description' => t('The insert, update or select will only be performed only if all required data are present'),
      '#description' => t('The insert, update or select will only be performed only if all required data are present'),
      '#default_value' => $optional
      '#default_value' => $optional
-  );  
+  );
   $form['edit_record']['disable'] = array(
   $form['edit_record']['disable'] = array(
      '#type' => 'checkbox',
      '#type' => 'checkbox',
      '#title' => t('Disable this record'),
      '#title' => t('Disable this record'),
@@ -882,6 +888,7 @@ function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state
     if ($form_state['values']['op'] ==  'Edit Record') {
     if ($form_state['values']['op'] ==  'Edit Record') {
 
 
       $template = $form_state['storage']['template_array'];
       $template = $form_state['storage']['template_array'];
+      $original_record_name = $template[ $form_state['storage']['original_priority'] ]['record_id'];
 
 
       // Edit Record
       // Edit Record
       $record = $template[ $form_state['storage']['original_priority'] ];
       $record = $template[ $form_state['storage']['original_priority'] ];
@@ -889,8 +896,8 @@ function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state
       $record['mode'] = $form_state['values']['mode'];
       $record['mode'] = $form_state['values']['mode'];
       $record['table'] = $form_state['values']['chado_table'];
       $record['table'] = $form_state['values']['chado_table'];
       $record['select_if_duplicate'] = $form_state['values']['select_if_duplicate'];
       $record['select_if_duplicate'] = $form_state['values']['select_if_duplicate'];
-      $record['update_if_duplicate'] = $form_state['values']['update_if_duplicate'];      
-      $record['select_optional'] = $form_state['values']['select_optional'];            
+      $record['update_if_duplicate'] = $form_state['values']['update_if_duplicate'];
+      $record['select_optional'] = $form_state['values']['select_optional'];
       $record['disable'] = $form_state['values']['disable'];
       $record['disable'] = $form_state['values']['disable'];
       $record['optional'] = $form_state['values']['optional'];
       $record['optional'] = $form_state['values']['optional'];
 
 
@@ -903,6 +910,19 @@ function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state
         $template[ $form_state['storage']['original_priority'] ] = $record;
         $template[ $form_state['storage']['original_priority'] ] = $record;
       }
       }
 
 
+      // Go through all records and update this record name where it was used for a foreign key
+      // Foreach field in each record that is of type: foreign key
+      foreach ($template as $priority => $record) {
+        foreach ($record['fields'] as $field_index => $field) {
+          if ($field['type'] === 'foreign key') {
+            // Check if this points to the old record name and if so, update it
+            if ($field['foreign key'] === $original_record_name) {
+              $template[$priority]['fields'][$field_index]['foreign key'] = $form_state['values']['record_name'];
+            }
+          }
+        }
+      }
+
       // Save Template
       // Save Template
       $form_state['storage']['template']->template_array = serialize($template);
       $form_state['storage']['template']->template_array = serialize($template);
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
@@ -1019,17 +1039,17 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
       $table = $form_state['storage']['template_array'][$priority]['table'];
       $table = $form_state['storage']['template_array'][$priority]['table'];
     }
     }
   }
   }
-  
+
   $show_all = $form_state['values']['show_all_records'];
   $show_all = $form_state['values']['show_all_records'];
-  
+
   $table_description = tripal_core_get_chado_table_schema($table);
   $table_description = tripal_core_get_chado_table_schema($table);
-  
+
   // Fields and foreign key / referral mappings
   // Fields and foreign key / referral mappings
   // build the fields array
   // build the fields array
   $chado_fields = array();
   $chado_fields = array();
   foreach ($table_description['fields'] as $field_name => $field_array) {
   foreach ($table_description['fields'] as $field_name => $field_array) {
     $chado_fields[$field_name] = $field_name;
     $chado_fields[$field_name] = $field_name;
-  }  
+  }
 
 
   $fk_options = array();
   $fk_options = array();
   $fk_options['NULL'] = 'None';
   $fk_options['NULL'] = 'None';
@@ -1053,7 +1073,7 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
     }
     }
     else {
     else {
       $field = current($chado_fields);
       $field = current($chado_fields);
-    } 
+    }
 
 
     // Foreign key options
     // Foreign key options
     $foreign_table = $foreign_field2table[$field];
     $foreign_table = $foreign_field2table[$field];
@@ -1071,26 +1091,26 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
       $fk_options[$record_name] = $record_name;
       $fk_options[$record_name] = $record_name;
     }
     }
   }
   }
-    
+
   // build the list of referrer table fields. This list is used
   // build the list of referrer table fields. This list is used
   // for the referring table field drop down. It has two groups
   // for the referring table field drop down. It has two groups
   // one for foreign keys and another for additional fields.
   // one for foreign keys and another for additional fields.
-  $ref_chado_fields = array();  
+  $ref_chado_fields = array();
   if ($field_type == 'foreign key') {
   if ($field_type == 'foreign key') {
-    $fk_rec = $form_state['values']['foreign_record']; 
+    $fk_rec = $form_state['values']['foreign_record'];
     if ($fk_rec and $fk_rec != 'None' and $fk_rec != 'NULL') {
     if ($fk_rec and $fk_rec != 'None' and $fk_rec != 'NULL') {
-    
+
       // first add in the foreign key field in the referring table
       // first add in the foreign key field in the referring table
       // that corresponds to this field (if one exists).
       // that corresponds to this field (if one exists).
       $fk_priority = $form_state['storage']['record2priority'][$fk_rec];
       $fk_priority = $form_state['storage']['record2priority'][$fk_rec];
       $fk_table = $form_state['storage']['template_array'][$fk_priority]['table'];
       $fk_table = $form_state['storage']['template_array'][$fk_priority]['table'];
       foreach ($table_description['foreign keys'] as $key_table => $key_array) {
       foreach ($table_description['foreign keys'] as $key_table => $key_array) {
         foreach ($key_array['columns'] as $left_field => $right_field) {
         foreach ($key_array['columns'] as $left_field => $right_field) {
-          if ($key_table == $fk_table and $left_field == $field) {                  
+          if ($key_table == $fk_table and $left_field == $field) {
             $ref_chado_fields['Foreign Key'][$right_field] = $right_field;
             $ref_chado_fields['Foreign Key'][$right_field] = $right_field;
           }
           }
         }
         }
-      }      
+      }
       // now add in the remaining fields of the referring record's table.
       // now add in the remaining fields of the referring record's table.
       $fk_description = tripal_core_get_chado_table_schema($fk_table);
       $fk_description = tripal_core_get_chado_table_schema($fk_table);
       foreach ($fk_description['fields'] as $fk_field_name => $fk_farray) {
       foreach ($fk_description['fields'] as $fk_field_name => $fk_farray) {
@@ -1105,6 +1125,38 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
     }
     }
   }
   }
 
 
+  // Ensure other field type fields are reset/cleared except for those of the current type
+  // ie: if the type is changed from spreadsheet column to constant, the spreadsheet column
+  // fields should be cleared since they don't apply to a constant
+  switch ($field_type) {
+    case 'table field':
+      // clear constant
+      $form_state['values']['constant_value'] = NULL;
+      // clear foreign key
+      // clears by default :)
+      break;
+    case 'constant':
+      // clear spreadsheet column
+      $form_state['values']['column_number'] = NULL;
+      $form_state['values']['column_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['column_exposed_desc'] = NULL;
+      $template_field['exposed_description'] = NULL;
+      // clear foreign key
+      // clears by default :)
+      break;
+    case 'foreign key':
+      // clear constant
+      $form_state['values']['constant_value'] = NULL;
+      // clear spreadsheet column
+      $form_state['values']['column_number'] = NULL;
+      $form_state['values']['column_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['column_exposed_desc'] = NULL;
+      $template_field['exposed_description'] = NULL;
+      break;
+  }
+
   // Start of Form Proper-------------------------------------------------------------
   // Start of Form Proper-------------------------------------------------------------
 
 
   $form['template_name'] = array(
   $form['template_name'] = array(
@@ -1210,7 +1262,7 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
       'effect' => 'fade'
       'effect' => 'fade'
     ),
     ),
   );
   );
-  
+
   // loading file data column
   // loading file data column
   $form['add_fields']['columns'] = array(
   $form['add_fields']['columns'] = array(
     '#type' => 'fieldset',
     '#type' => 'fieldset',
@@ -1228,7 +1280,7 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
     '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
     '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
   );
   );
   */
   */
-  
+
   $form['add_fields']['columns']['column_number'] = array(
   $form['add_fields']['columns']['column_number'] = array(
     '#type' => 'textfield',
     '#type' => 'textfield',
     '#title' => t('Column'),
     '#title' => t('Column'),
@@ -1285,7 +1337,7 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
     '#collapsible' => TRUE,
     '#collapsible' => TRUE,
     '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
     '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
   );
   );
-  
+
   $form['add_fields']['foreign_key']['show_all_records'] = array(
   $form['add_fields']['foreign_key']['show_all_records'] = array(
     '#type' => 'checkbox',
     '#type' => 'checkbox',
     '#title' => 'Refer to any record',
     '#title' => 'Refer to any record',
@@ -1295,9 +1347,9 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
       'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
       'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'effect' => 'fade'
       'effect' => 'fade'
-    ),    
+    ),
   );
   );
-  
+
   $form['add_fields']['foreign_key']['foreign_record'] = array(
   $form['add_fields']['foreign_key']['foreign_record'] = array(
     '#type' => 'select',
     '#type' => 'select',
     '#title' => 'Record to refer to',
     '#title' => 'Record to refer to',
@@ -1307,10 +1359,10 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
       'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
       'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'effect' => 'fade'
       'effect' => 'fade'
-    ),  
+    ),
     '#default_value' => ($form_state['values']['foreign_record']) ? $form_state['values']['foreign_record'] : $template_field['foreign key'],
     '#default_value' => ($form_state['values']['foreign_record']) ? $form_state['values']['foreign_record'] : $template_field['foreign key'],
   );
   );
-  
+
   $form['add_fields']['foreign_key']['foreign_field'] = array(
   $form['add_fields']['foreign_key']['foreign_field'] = array(
     '#type' => 'select',
     '#type' => 'select',
     '#title' => 'Field to refer to',
     '#title' => 'Field to refer to',
@@ -1318,8 +1370,8 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
     '#options' => $ref_chado_fields,
     '#options' => $ref_chado_fields,
     '#default_value' => ($form_state['values']['foreign_field']) ? $form_state['values']['foreign_field'] : $template_field['foreign_field'],
     '#default_value' => ($form_state['values']['foreign_field']) ? $form_state['values']['foreign_field'] : $template_field['foreign_field'],
   );
   );
-  
-  
+
+
   $form['add_fields']['additional'] = array(
   $form['add_fields']['additional'] = array(
     '#type' => 'fieldset',
     '#type' => 'fieldset',
     '#title' => 'Additional Options',
     '#title' => 'Additional Options',
@@ -1327,7 +1379,8 @@ function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
 
 
   $form['add_fields']['additional']['required'] = array(
   $form['add_fields']['additional']['required'] = array(
     '#type' => 'checkbox',
     '#type' => 'checkbox',
-    '#title' => 'Make this file required',
+    '#title' => 'Make this field required',
+    '#default_value' => (!empty($form_state['values']['required'])) ? $form_state['values']['required'] : $template_field['required'],
   );
   );
 
 
   $form['add_fields']['additional']['regex_transform'] = array(
   $form['add_fields']['additional']['regex_transform'] = array(
@@ -1611,8 +1664,8 @@ function tripal_bulk_loader_add_template_field_form_submit($form, &$form_state)
       }
       }
 
 
       // sort new regex arrays
       // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
+      ksort($new_regex['pattern']);
+      ksort($new_regex['replace']);
 
 
       $form_state['storage']['regex'] = $new_regex;
       $form_state['storage']['regex'] = $new_regex;
     }
     }
@@ -1696,6 +1749,12 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
     $form_state['storage']['original_field']['priority'] = $priority;
     $form_state['storage']['original_field']['priority'] = $priority;
     $form_state['storage']['original_field']['field_index'] = $field_index;
     $form_state['storage']['original_field']['field_index'] = $field_index;
   }
   }
+  // get field from the form_state
+  elseif (!empty($form_state['storage']['original_field']['priority']) && !empty($form_state['storage']['original_field']['field_index'])) {
+    $priority = $form_state['storage']['original_field']['priority'];
+    $field_index = $form_state['storage']['original_field']['field_index'];
+    $template_field = $form_state['storage']['template_array'][$priority]['fields'][$field_index];
+  }
 
 
   $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
   $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
 
 
@@ -1716,13 +1775,13 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
   $chado_fields = array();
   $chado_fields = array();
   foreach ($table_description['fields'] as $field_name => $field_array) {
   foreach ($table_description['fields'] as $field_name => $field_array) {
     $chado_fields[$field_name] = $field_name;
     $chado_fields[$field_name] = $field_name;
-  }  
+  }
 
 
   $ref_chado_fields = array();
   $ref_chado_fields = array();
   $fk_options = array();
   $fk_options = array();
   $fk_options['NULL'] = 'None';
   $fk_options['NULL'] = 'None';
   if ($field_type == 'foreign key' and !$show_all) {
   if ($field_type == 'foreign key' and !$show_all) {
-  
+
     $foreign_field2table = array();
     $foreign_field2table = array();
     foreach ($table_description['foreign keys'] as $key_table => $key_array) {
     foreach ($table_description['foreign keys'] as $key_table => $key_array) {
       foreach ($key_array['columns'] as $left_field => $right_field) {
       foreach ($key_array['columns'] as $left_field => $right_field) {
@@ -1762,26 +1821,26 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
       $fk_options[$record_name] = $record_name;
       $fk_options[$record_name] = $record_name;
     }
     }
   }
   }
-  
+
   // build the list of referrer table fields
   // build the list of referrer table fields
   if ($field_type == 'foreign key') {
   if ($field_type == 'foreign key') {
     $fk_rec = $form_state['values']['foreign_record'] ?  $form_state['values']['foreign_record'] : $template_field['foreign key'];
     $fk_rec = $form_state['values']['foreign_record'] ?  $form_state['values']['foreign_record'] : $template_field['foreign key'];
     if ($fk_rec and $fk_rec != 'None' and $fk_rec != 'NULL') {
     if ($fk_rec and $fk_rec != 'None' and $fk_rec != 'NULL') {
-    
+
       // first add in the foreign keys
       // first add in the foreign keys
       $fk_priority = $form_state['storage']['record2priority'][$fk_rec];
       $fk_priority = $form_state['storage']['record2priority'][$fk_rec];
       $fk_table = $form_state['storage']['template_array'][$fk_priority]['table'];
       $fk_table = $form_state['storage']['template_array'][$fk_priority]['table'];
       foreach ($table_description['foreign keys'] as $key_table => $key_array) {
       foreach ($table_description['foreign keys'] as $key_table => $key_array) {
         foreach ($key_array['columns'] as $left_field => $right_field) {
         foreach ($key_array['columns'] as $left_field => $right_field) {
-          if ($key_table == $fk_table and $left_field == $field) {                  
+          if ($key_table == $fk_table and $left_field == $field) {
             $ref_chado_fields['Foreign Key'][$right_field] = $right_field;
             $ref_chado_fields['Foreign Key'][$right_field] = $right_field;
           }
           }
         }
         }
-      }      
+      }
       $fk_description = tripal_core_get_chado_table_schema($fk_table);
       $fk_description = tripal_core_get_chado_table_schema($fk_table);
       foreach ($fk_description['fields'] as $fk_field_name => $fk_farray) {
       foreach ($fk_description['fields'] as $fk_field_name => $fk_farray) {
          // don't include the FK field it's included above
          // don't include the FK field it's included above
-         if (in_array('Foreign Key', $ref_chado_fields) and 
+         if (in_array('Foreign Key', $ref_chado_fields) and
              in_array($fk_field_name, $ref_chado_fields['Foreign Key'])) {
              in_array($fk_field_name, $ref_chado_fields['Foreign Key'])) {
            continue;
            continue;
          }
          }
@@ -1790,6 +1849,47 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
     }
     }
   }
   }
 
 
+  // Ensure other field type fields are reset/cleared except for those of the current type
+  // ie: if the type is changed from spreadsheet column to constant, the spreadsheet column
+  // fields should be cleared since they don't apply to a constant
+  switch ($field_type) {
+    case 'table field':
+      // clear constant
+      $form_state['values']['constant_value'] = NULL;
+      $template_field['constant value'] = NULL;
+      $form_state['values']['constant_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['constant_validate'] = NULL;
+      $template_field['exposed_validate'] = NULL;
+      // clear foreign key
+      // clears by default :)
+      break;
+    case 'constant':
+      // clear spreadsheet column
+      $form_state['values']['column_number'] = NULL;
+      $form_state['values']['column_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['column_exposed_desc'] = NULL;
+      $template_field['exposed_description'] = NULL;
+      // clear foreign key
+      // clears by default :)
+      break;
+    case 'foreign key':
+      // clear constant
+      $form_state['values']['constant_value'] = NULL;
+      $template_field['constant value'] = NULL;
+      $form_state['values']['constant_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['constant_validate'] = NULL;
+      $template_field['exposed_validate'] = NULL;
+      // clear spreadsheet column
+      $form_state['values']['column_number'] = NULL;
+      $form_state['values']['column_exposed'] = NULL;
+      $template_field['exposed'] = NULL;
+      $form_state['values']['column_exposed_desc'] = NULL;
+      $template_field['exposed_description'] = NULL;
+      break;
+  }
 
 
   // Start of Form Proper--------------------------------------------------------------
   // Start of Form Proper--------------------------------------------------------------
 
 
@@ -1864,7 +1964,7 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
     '#title' => t('Human-readable Title for Field'),
     '#title' => t('Human-readable Title for Field'),
     '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
     '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
   );
   );
-  
+
    // Chado Field
    // Chado Field
   $form['edit_fields']['chado'] = array(
   $form['edit_fields']['chado'] = array(
     '#type' => 'fieldset',
     '#type' => 'fieldset',
@@ -1972,7 +2072,7 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
     '#collapsible' => TRUE,
     '#collapsible' => TRUE,
     '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
     '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
   );
   );
-  
+
   $form['edit_fields']['foreign_key']['show_all_records'] = array(
   $form['edit_fields']['foreign_key']['show_all_records'] = array(
     '#type' => 'checkbox',
     '#type' => 'checkbox',
     '#title' => 'Refer to any record',
     '#title' => 'Refer to any record',
@@ -1982,9 +2082,9 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
       'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
       'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'effect' => 'fade'
       'effect' => 'fade'
-    ),    
+    ),
   );
   );
-  
+
   $form['edit_fields']['foreign_key']['foreign_record'] = array(
   $form['edit_fields']['foreign_key']['foreign_record'] = array(
     '#type' => 'select',
     '#type' => 'select',
     '#title' => 'Record to refer to',
     '#title' => 'Record to refer to',
@@ -1994,10 +2094,10 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
       'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
       'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'wrapper' => 'tripal_bulk_loader_template-add_field',
       'effect' => 'fade'
       'effect' => 'fade'
-    ),  
+    ),
     '#default_value' => ($form_state['values']['foreign_record']) ? $form_state['values']['foreign_record'] : $template_field['foreign key'],
     '#default_value' => ($form_state['values']['foreign_record']) ? $form_state['values']['foreign_record'] : $template_field['foreign key'],
   );
   );
-  
+
   $form['edit_fields']['foreign_key']['foreign_field'] = array(
   $form['edit_fields']['foreign_key']['foreign_field'] = array(
     '#type' => 'select',
     '#type' => 'select',
     '#title' => 'Field to refer to',
     '#title' => 'Field to refer to',
@@ -2006,7 +2106,7 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
     '#default_value' => ($form_state['values']['foreign_field']) ? $form_state['values']['foreign_field'] : $template_field['foreign field'],
     '#default_value' => ($form_state['values']['foreign_field']) ? $form_state['values']['foreign_field'] : $template_field['foreign field'],
   );
   );
 
 
- 
+
 
 
   $form['edit_fields']['additional'] = array(
   $form['edit_fields']['additional'] = array(
     '#type' => 'fieldset',
     '#type' => 'fieldset',
@@ -2016,7 +2116,7 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
   $form['edit_fields']['additional']['required'] = array(
   $form['edit_fields']['additional']['required'] = array(
     '#type' => 'checkbox',
     '#type' => 'checkbox',
     '#title' => 'Make this field required',
     '#title' => 'Make this field required',
-    '#default_value' => $template_field['required'],
+    '#default_value' => (!empty($form_state['values']['required'])) ? $form_state['values']['required'] : $template_field['required'],
   );
   );
 
 
   $form['edit_fields']['additional']['regex_transform'] = array(
   $form['edit_fields']['additional']['regex_transform'] = array(
@@ -2041,6 +2141,14 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
   $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
   $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
     '#tree' => TRUE,
     '#tree' => TRUE,
   );
   );
+
+  if (!is_array($template_field['regex']['pattern'])) {
+    $template_field['regex']['pattern'] = array();
+  }
+  $key_options = array();
+  foreach ($template_field['regex']['pattern'] as $k => $v) {
+    $key_options[$k] = $k;
+  }
   foreach ($template_field['regex']['pattern'] as $index => $pattern) {
   foreach ($template_field['regex']['pattern'] as $index => $pattern) {
     $data_element = array(
     $data_element = array(
       'pattern' => array(
       'pattern' => array(
@@ -2057,7 +2165,7 @@ function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
       ),
       ),
       'new_index' => array(
       'new_index' => array(
         '#type' => 'select',
         '#type' => 'select',
-        '#options' => range(0, sizeof($template_field['regex']['pattern'])-1),
+        '#options' => $key_options,
         '#default_value' => $index,
         '#default_value' => $index,
       ),
       ),
       'id' => array(
       'id' => array(
@@ -2188,7 +2296,6 @@ function tripal_bulk_loader_edit_template_field_form_validate($form, $form_state
 function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
 function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
 
 
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  //dpm($op, 'Operation Submitted');
 
 
   //Clear Test
   //Clear Test
   $form_state['storage']['test_regex_result'] = NULL;
   $form_state['storage']['test_regex_result'] = NULL;
@@ -2307,22 +2414,6 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
       $field_index = $form_state['storage']['original_field']['field_index'];
       $field_index = $form_state['storage']['original_field']['field_index'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
 
 
-      // Save Template
-      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
-      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
-
-      if ($success) {
-        drupal_set_message(t('Successfully Added Transformation Rule'));
-        drupal_set_message(t('Template Saved.'));
-      }
-      else {
-        drupal_set_message(t('Unable to Save Template!'), 'error');
-        watchdog('T_bulk_loader',
-          'Unable to save bulk loader template: %template',
-          array('%template' => print_r($form_state['storage']['template'], TRUE)),
-          WATCHDOG_ERROR
-        );
-      }
     }
     }
     elseif ($op == 'Save Transformation Rule Order') {
     elseif ($op == 'Save Transformation Rule Order') {
 
 
@@ -2335,8 +2426,8 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
       }
       }
 
 
       // sort new regex arrays
       // sort new regex arrays
-      asort($new_regex['pattern']);
-      asort($new_regex['replace']);
+      ksort($new_regex['pattern']);
+      ksort($new_regex['replace']);
 
 
       // Add back to original field
       // Add back to original field
       $form_state['storage']['original_field']['regex'] = $new_regex;
       $form_state['storage']['original_field']['regex'] = $new_regex;
@@ -2344,6 +2435,7 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
       $field_index = $form_state['storage']['original_field']['field_index'];
       $field_index = $form_state['storage']['original_field']['field_index'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
 
 
+      /**
       // Save Template
       // Save Template
       $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
       $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
@@ -2360,6 +2452,7 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
           WATCHDOG_ERROR
           WATCHDOG_ERROR
         );
         );
       }
       }
+      */
     }
     }
     elseif ($op == 'Delete Transformation') {
     elseif ($op == 'Delete Transformation') {
 
 
@@ -2372,6 +2465,7 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
       $field_index = $form_state['storage']['original_field']['field_index'];
       $field_index = $form_state['storage']['original_field']['field_index'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
       $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
 
 
+      /**
       // Save Template
       // Save Template
       $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
       $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
       $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
@@ -2388,6 +2482,7 @@ function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state)
           WATCHDOG_ERROR
           WATCHDOG_ERROR
         );
         );
       }
       }
+      */
 
 
     }
     }
     elseif ($op == 'Test Transformation Rules') {
     elseif ($op == 'Test Transformation Rules') {

+ 108 - 102
tripal_bulk_loader/tripal_bulk_loader.loader.inc

@@ -200,23 +200,23 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
       elseif (preg_match('/foreign key/', $field_array['type'])) {
       elseif (preg_match('/foreign key/', $field_array['type'])) {
         $default_data[$priority]['values_array'][$field_array['field']] = array();
         $default_data[$priority]['values_array'][$field_array['field']] = array();
         $default_data[$priority]['need_further_processing'] = TRUE;
         $default_data[$priority]['need_further_processing'] = TRUE;
-        $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['record'] = $field_array['foreign key'];        
-        
+        $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['record'] = $field_array['foreign key'];
+
         // Add in the FK / Referral table
         // Add in the FK / Referral table
         $fk_priority = $record2priority[$field_array['foreign key']];
         $fk_priority = $record2priority[$field_array['foreign key']];
-        $fk_table = $template_array[$fk_priority]['table'];    
+        $fk_table = $template_array[$fk_priority]['table'];
         $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['table'] = $fk_table;
         $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['table'] = $fk_table;
-        
+
         // Add in the FK / Referral field
         // Add in the FK / Referral field
         // for backwards compatibility we need to get the FK relationship to find
         // for backwards compatibility we need to get the FK relationship to find
-        // out what field we're joining on.  For templates created using a 
+        // out what field we're joining on.  For templates created using a
         // previous version it was assumed that the FK field was always the field to join
         // previous version it was assumed that the FK field was always the field to join
         if (!array_key_exists('foreign field', $field_array)) {
         if (!array_key_exists('foreign field', $field_array)) {
           $tbl_description = tripal_core_get_chado_table_schema($record_array['table']);
           $tbl_description = tripal_core_get_chado_table_schema($record_array['table']);
           foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
           foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
             if ($key_table == $fk_table) {
             if ($key_table == $fk_table) {
               foreach ($key_array['columns'] as $left_field => $right_field) {
               foreach ($key_array['columns'] as $left_field => $right_field) {
-                if ($left_field == $field_array['field']) {                  
+                if ($left_field == $field_array['field']) {
                   $field_array['foreign field'] = $right_field;
                   $field_array['foreign field'] = $right_field;
                 }
                 }
               }
               }
@@ -280,9 +280,9 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
     // Open File
     // Open File
     print "\tPreparing to load the current constant set...\n";
     print "\tPreparing to load the current constant set...\n";
     print "\t\tOpen File...\n";
     print "\t\tOpen File...\n";
-    $file = new SplFileObject($node->file, 'r'); 
-    if (!$file) { 
-      watchdog('T_bulk_loader', 'Could not open file %file', 
+    $file = new SplFileObject($node->file, 'r');
+    if (!$file) {
+      watchdog('T_bulk_loader', 'Could not open file %file',
         array($node->file), WATCHDOG_ERROR);
         array($node->file), WATCHDOG_ERROR);
       return;
       return;
     }
     }
@@ -290,7 +290,7 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
     // Set defaults
     // Set defaults
     $header = '';
     $header = '';
     if (preg_match('/(t|true|1)/', $node->file_has_header)) {
     if (preg_match('/(t|true|1)/', $node->file_has_header)) {
-      $file->next();      
+      $file->next();
       $header = $file->current();
       $header = $file->current();
     }
     }
     $num_records = 0;
     $num_records = 0;
@@ -342,7 +342,7 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
     tripal_bulk_loader_progress_bar(0, $total_lines);
     tripal_bulk_loader_progress_bar(0, $total_lines);
     while (!$file->eof()) {
     while (!$file->eof()) {
       $file->next();
       $file->next();
-      $raw_line = $file->current();  
+      $raw_line = $file->current();
       $raw_line = trim($raw_line);
       $raw_line = trim($raw_line);
       if (empty($raw_line)) {
       if (empty($raw_line)) {
         continue;
         continue;
@@ -352,7 +352,7 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
 
 
       // update the job status every 1% of lines processed for the current group
       // update the job status every 1% of lines processed for the current group
       if ($node->job_id and $num_lines % $interval == 0) {
       if ($node->job_id and $num_lines % $interval == 0) {
-      
+
         // percentage of lines processed for the current group
         // percentage of lines processed for the current group
         $group_progress = round(($num_lines / $total_lines) * 100);
         $group_progress = round(($num_lines / $total_lines) * 100);
         tripal_bulk_loader_progress_bar($num_lines, $total_lines);
         tripal_bulk_loader_progress_bar($num_lines, $total_lines);
@@ -386,11 +386,11 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
 
 
         // execute all records that are not disabled
         // execute all records that are not disabled
         $no_errors = FALSE;
         $no_errors = FALSE;
-        if (array_key_exists($priority, $data) and 
-            array_key_exists('disabled', $data[$priority]) and 
+        if (array_key_exists($priority, $data) and
+            array_key_exists('disabled', $data[$priority]) and
             $data[$priority]['disabled'] == 0) {
             $data[$priority]['disabled'] == 0) {
           $no_errors = process_data_array_for_line($priority, $data, $default_data, $options);
           $no_errors = process_data_array_for_line($priority, $data, $default_data, $options);
-        } 
+        }
         else {
         else {
           // set status to true for skipped records
           // set status to true for skipped records
           $no_errors = TRUE;
           $no_errors = TRUE;
@@ -405,7 +405,7 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
           }
           }
           $failed = TRUE;
           $failed = TRUE;
           break;
           break;
-        } 
+        }
       } // end of foreach table in default data array
       } // end of foreach table in default data array
 
 
       tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
       tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
@@ -425,7 +425,7 @@ function tripal_bulk_loader_load_data($nid, $job_id) {
             tripal_db_set_savepoint_transaction($savepoint, TRUE);
             tripal_db_set_savepoint_transaction($savepoint, TRUE);
           }
           }
         }
         }
-      } 
+      }
     } //end of foreach line of file
     } //end of foreach line of file
 
 
     // END Transaction
     // END Transaction
@@ -477,13 +477,13 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
   $table = $table_data['table'];
   $table = $table_data['table'];
   $values = $table_data['values_array'];
   $values = $table_data['values_array'];
 
 
-  // populate the values array with real value either from the input data file line 
+  // populate the values array with real value either from the input data file line
   // or from the foreign key / referral record
   // or from the foreign key / referral record
-  if (array_key_exists('need_further_processing', $table_data) and $table_data['need_further_processing']) {   
+  if (array_key_exists('need_further_processing', $table_data) and $table_data['need_further_processing']) {
     if (array_key_exists($priority, $addt->field2column)) {
     if (array_key_exists($priority, $addt->field2column)) {
       $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
       $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
-    } 
-    $values = tripal_bulk_loader_add_foreignkey_to_values($table_data, $values, $data, $addt->record2priority, $addt->nid, $priority, $default_data);    
+    }
+    $values = tripal_bulk_loader_add_foreignkey_to_values($table_data, $values, $data, $addt->record2priority, $addt->nid, $priority, $default_data);
   }
   }
 
 
   $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
   $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
@@ -492,20 +492,20 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
   }
   }
 
 
   // get the table description
   // get the table description
-  $table_desc = tripal_core_get_chado_table_schema($table);  
-  
-  // Check that template required fields are present. if a required field is 
+  $table_desc = tripal_core_get_chado_table_schema($table);
+
+  // Check that template required fields are present. if a required field is
   // missing and this
   // missing and this
   // is an optional record then just return. otherwise raise an error
   // is an optional record then just return. otherwise raise an error
   $skip_optional = 0;
   $skip_optional = 0;
   foreach ($table_data['required'] as $field => $required) {
   foreach ($table_data['required'] as $field => $required) {
     if ($required) {
     if ($required) {
       // check if the field has no value (or array is empty)
       // check if the field has no value (or array is empty)
-      if (!isset($values[$field]) or 
+      if (!isset($values[$field]) or
           (is_array($values[$field]) and count($values[$field]) == 0)) {
           (is_array($values[$field]) and count($values[$field]) == 0)) {
         // check if the record is optional.  For backwards compatiblity we need to
         // check if the record is optional.  For backwards compatiblity we need to
         // check if the 'mode' is set to 'optional'
         // check if the 'mode' is set to 'optional'
-        if ($table_data['optional'] or preg_match('/optional/', $table_data['mode']) or 
+        if ($table_data['optional'] or preg_match('/optional/', $table_data['mode']) or
             $table_data['select_optional'])  {
             $table_data['select_optional'])  {
           $skip_optional = 1;
           $skip_optional = 1;
           // set the values array to be empty since we all required fields are
           // set the values array to be empty since we all required fields are
@@ -514,7 +514,7 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
           $values = array();
           $values = array();
         }
         }
         else {
         else {
-          $msg = "\nLine " . $addt->line_num . ' "' . $table_data['record_id'] . 
+          $msg = "\nLine " . $addt->line_num . ' "' . $table_data['record_id'] .
             '" (' . $table_data['mode'] . ') Missing template required value: ' . $table . '.' . $field;
             '" (' . $table_data['mode'] . ') Missing template required value: ' . $table . '.' . $field;
           watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
           watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
           $data[$priority]['error'] = TRUE;
           $data[$priority]['error'] = TRUE;
@@ -523,71 +523,75 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
       }
       }
     }
     }
   }
   }
-  
+
   // for an insert, check that all database required fields are present in the values array
   // for an insert, check that all database required fields are present in the values array
-  // we check for 'optional' in the mode for backwards compatibility. The 'optional' 
+  // we check for 'optional' in the mode for backwards compatibility. The 'optional'
   // mode used to be a type of insert
   // mode used to be a type of insert
-  if (!$skip_optional and (preg_match('/insert/', $table_data['mode']) or 
+  if (!$skip_optional and (preg_match('/insert/', $table_data['mode']) or
        preg_match('/optional/', $table_data['mode']))) {
        preg_match('/optional/', $table_data['mode']))) {
     // Check all database table required fields are set
     // Check all database table required fields are set
     $fields = $table_desc['fields'];
     $fields = $table_desc['fields'];
-    foreach ($fields as $field => $def) {   
+    foreach ($fields as $field => $def) {
       // a field is considered missing if it cannot be null and there is no default
       // a field is considered missing if it cannot be null and there is no default
       // value for it or it is not of type 'serial'
       // value for it or it is not of type 'serial'
       if (array_key_exists('not null', $def) and $def['not null'] == 1 and   // field must have a value
       if (array_key_exists('not null', $def) and $def['not null'] == 1 and   // field must have a value
           !array_key_exists($field, $values) and                             // there is not a value for it
           !array_key_exists($field, $values) and                             // there is not a value for it
           !array_key_exists('default', $def) and                             // there is no default for it
           !array_key_exists('default', $def) and                             // there is no default for it
           strcmp($def['type'], 'serial') != 0) {                             // it is not a 'serial' type column
           strcmp($def['type'], 'serial') != 0) {                             // it is not a 'serial' type column
-        $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . 
+        $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] .
                ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
                ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
-        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR); 
+        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
         $data[$priority]['error'] = TRUE;
         $data[$priority]['error'] = TRUE;
-      } 
-    } 
-  } 
-  
+      }
+    }
+  }
+
   // add updated values array into the data array
   // add updated values array into the data array
   $data[$priority]['values_array'] = $values;
   $data[$priority]['values_array'] = $values;
-  
+
   // if there was an error already -> don't insert
   // if there was an error already -> don't insert
   if (array_key_exists('error', $data[$priority]) and $data[$priority]['error']) {
   if (array_key_exists('error', $data[$priority]) and $data[$priority]['error']) {
+    watchdog('T_bulk_loader','Skipping processing of %table due to previous errors',array('%table'=>$table),WATCHDOG_NOTICE);
     return $no_errors;
     return $no_errors;
   }
   }
-  
-  // skip optional fields 
+
+  // skip optional fields
   if ($skip_optional) {
   if ($skip_optional) {
+    watchdog('T_bulk_loader','Skipping an optional record (%record)',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
     return $no_errors;
     return $no_errors;
   }
   }
-  
+
   // check if it is already inserted
   // check if it is already inserted
   if (array_key_exists('inserted', $table_data) and $table_data['inserted']) {
   if (array_key_exists('inserted', $table_data) and $table_data['inserted']) {
+    watchdog('T_bulk_loader','Skipping %record since it is already inserted',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
     return $no_errors;
     return $no_errors;
   }
   }
-  
+
   // check if it is already selected, if so, just get the value stored in
   // check if it is already selected, if so, just get the value stored in
   // the default_data array
   // the default_data array
   if (array_key_exists('selected', $table_data) and $table_data['selected']) {
   if (array_key_exists('selected', $table_data) and $table_data['selected']) {
     $data[$priority]['values_array'] = $default_data[$priority]['values_array'];
     $data[$priority]['values_array'] = $default_data[$priority]['values_array'];
+    watchdog('T_bulk_loader','%record was already selected thus we are just returning the values previously selected.',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
     return $no_errors;
     return $no_errors;
   }
   }
 
 
   // make sure we have some value in the select_if_duplicate and update_if_duplicate options
   // make sure we have some value in the select_if_duplicate and update_if_duplicate options
   if (!array_key_exists('select_if_duplicate', $table_data)) {
   if (!array_key_exists('select_if_duplicate', $table_data)) {
     $table_data['select_if_duplicate'] = 0;
     $table_data['select_if_duplicate'] = 0;
-  } 
+  }
   if (!array_key_exists('update_if_duplicate', $table_data)) {
   if (!array_key_exists('update_if_duplicate', $table_data)) {
     $table_data['update_if_duplicate'] = 0;
     $table_data['update_if_duplicate'] = 0;
-  } 
-  
-  // if "select if duplicate" is enabled then check to ensure unique constraint is not violoated.  
+  }
+
+  // if "select if duplicate" is enabled then check to ensure unique constraint is not violoated.
   // If it is violoated then simply return, the record already exists in the database.
   // If it is violoated then simply return, the record already exists in the database.
   // We check for "insert_unique" for backwards compatibilty but that mode no longer exists
   // We check for "insert_unique" for backwards compatibilty but that mode no longer exists
   $data[$priority]['is_duplicate'] = 0;
   $data[$priority]['is_duplicate'] = 0;
-  if (preg_match('/insert_unique/', $table_data['mode']) or 
+  if (preg_match('/insert_unique/', $table_data['mode']) or
      $table_data['select_if_duplicate'] == 1 or $table_data['update_if_duplicate'] == 1) {
      $table_data['select_if_duplicate'] == 1 or $table_data['update_if_duplicate'] == 1) {
     $options = array('is_duplicate' => TRUE);
     $options = array('is_duplicate' => TRUE);
     $duplicate = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, $options);
     $duplicate = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, $options);
-    
+
     // if this is a duplicate then substitute the values in the table_data array so
     // if this is a duplicate then substitute the values in the table_data array so
     // that for future records that my depend on this one, they can get the values needed
     // that for future records that my depend on this one, they can get the values needed
     if ($duplicate and is_array($duplicate) and count($duplicate) == 1) {
     if ($duplicate and is_array($duplicate) and count($duplicate) == 1) {
@@ -597,29 +601,30 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
       $data[$priority]['is_duplicate'] = (array) $dup_record;
       $data[$priority]['is_duplicate'] = (array) $dup_record;
 
 
       // if all we have is one field then we will just use the value returned
       // if all we have is one field then we will just use the value returned
-      // rather than create an array of values. This way it will prevent 
-      // the tripal_core_chado_(select|insert|update) from recursing on 
+      // rather than create an array of values. This way it will prevent
+      // the tripal_core_chado_(select|insert|update) from recursing on
       // foreign keys and make the loader go faster.
       // foreign keys and make the loader go faster.
       if (count((array) $dup_record) == 1) {
       if (count((array) $dup_record) == 1) {
-        foreach ($dup_record as $key => $value) { 
+        foreach ($dup_record as $key => $value) {
           $data[$priority]['values_array'] = $value;
           $data[$priority]['values_array'] = $value;
-        } 
+        }
       }
       }
       // if we have multiple fields returned then we need to set the values
       // if we have multiple fields returned then we need to set the values
       // the new array.
       // the new array.
       else {
       else {
         // convert object to array
         // convert object to array
         $new_values = array();
         $new_values = array();
-        foreach ($dup_record as $key => $value) { 
+        foreach ($dup_record as $key => $value) {
           $new_values[$key] = $value;
           $new_values[$key] = $value;
-        } 
-        $data[$priority]['values_array'] = $new_values;        
+        }
+        $data[$priority]['values_array'] = $new_values;
       }
       }
       // return if this is a select_if_duplicate
       // return if this is a select_if_duplicate
       if ($table_data['select_if_duplicate'] == 1) {
       if ($table_data['select_if_duplicate'] == 1) {
+        watchdog('T_bulk_loader','Simply returning values for %record since it was already inserted',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
         return $no_errors;
         return $no_errors;
       }
       }
-    } 
+    }
   }
   }
   else {
   else {
     # TODO: what to do if there are more than one value returned when
     # TODO: what to do if there are more than one value returned when
@@ -650,21 +655,21 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
       $record = tripal_core_chado_update($table, $match, $values, $options);
       $record = tripal_core_chado_update($table, $match, $values, $options);
     }
     }
     else {
     else {
-      $record = tripal_core_chado_insert($table, $values, $options);      
+      $record = tripal_core_chado_insert($table, $values, $options);
     }
     }
 
 
     // if the insert was not successful
     // if the insert was not successful
     if (!$record) {
     if (!$record) {
-      $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . 
-        $table_data['mode'] . ') Unable to insert record into ' . $table . 
+      $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
+        $table_data['mode'] . ') Unable to insert record into ' . $table .
         ' where values:' . print_r($values, TRUE);
         ' where values:' . print_r($values, TRUE);
-        
+
       watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
       watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
       $data[$priority]['error'] = TRUE;
       $data[$priority]['error'] = TRUE;
       $no_errors = FALSE;
       $no_errors = FALSE;
     }
     }
     // if the insert was succesful
     // if the insert was succesful
-    else {    
+    else {
 
 
       // if mode=insert_once then ensure we only insert it once
       // if mode=insert_once then ensure we only insert it once
       if (preg_match('/insert_once/', $table_data['mode'])) {
       if (preg_match('/insert_once/', $table_data['mode'])) {
@@ -679,24 +684,24 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
           $addt->nid
           $addt->nid
         ));
         ));
         if ($insert_record) {
         if ($insert_record) {
-          $insert_record->ids_inserted .= ',' . $values[$table_desc['primary key'][0] ];
+          $insert_record->ids_inserted .= ',' . $record[$table_desc['primary key'][0] ];
           drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
           drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
           //print 'Update: '.print_r($insert_record,TRUE)."\n";
           //print 'Update: '.print_r($insert_record,TRUE)."\n";
-          return $no_errors;
+          //return $no_errors;
         }
         }
         else {
         else {
           $insert_record = array(
           $insert_record = array(
             'nid' => $addt->nid,
             'nid' => $addt->nid,
             'table_inserted_into' => $table,
             'table_inserted_into' => $table,
             'table_primary_key' => $table_desc['primary key'][0],
             'table_primary_key' => $table_desc['primary key'][0],
-            'ids_inserted' => $values[ $table_desc['primary key'][0] ],
+            'ids_inserted' => $record[ $table_desc['primary key'][0] ],
           );
           );
           //print 'New: '.print_r($insert_record,TRUE)."\n";
           //print 'New: '.print_r($insert_record,TRUE)."\n";
           $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
           $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
-          return $no_errors;
+          //return $no_errors;
         }//end of if insert record
         }//end of if insert record
       }// end of if keeping track of records inserted
       }// end of if keeping track of records inserted
-    
+
       // substitute the values array for the primary key if it exists
       // substitute the values array for the primary key if it exists
       // and is a single field
       // and is a single field
       if (array_key_exists('primary key', $table_desc)) {
       if (array_key_exists('primary key', $table_desc)) {
@@ -704,7 +709,7 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
           $pkey_field = $table_desc['primary key'][0];
           $pkey_field = $table_desc['primary key'][0];
           $data[$priority]['values_array'] = $record[$pkey_field];
           $data[$priority]['values_array'] = $record[$pkey_field];
         }
         }
-      } 
+      }
       else {
       else {
         //add changes back to values array
         //add changes back to values array
         $data[$priority]['values_array'] = $record;
         $data[$priority]['values_array'] = $record;
@@ -722,7 +727,7 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
     // if the record doesn't exist and it's not optional then generate an error
     // if the record doesn't exist and it's not optional then generate an error
     if (count($matches) == 0) {
     if (count($matches) == 0) {
       // No record on select
       // No record on select
-      if ($table_data['select_optional'] != 1) {        
+      if ($table_data['select_optional'] != 1) {
         $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
         $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
         $data[$priority]['error'] = TRUE;
         $data[$priority]['error'] = TRUE;
@@ -735,33 +740,34 @@ function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
       }
       }
     }
     }
     // if we have more than one record matching and this select isn't optional then fail
     // if we have more than one record matching and this select isn't optional then fail
-    if (count($matches) > 1) { 
+    if (count($matches) > 1) {
       if ($table_data['select_optional'] != 1) {
       if ($table_data['select_optional'] != 1) {
         $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
         $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
         $data[$priority]['error'] = TRUE;
         $data[$priority]['error'] = TRUE;
         $no_errors = FALSE;
         $no_errors = FALSE;
-      } 
+      }
       // there are too many matches and this is an optional select so set
       // there are too many matches and this is an optional select so set
       // the values to empty for any records with an FK relationship on this one
       // the values to empty for any records with an FK relationship on this one
       else {
       else {
         $data[$priority]['values_array'] = NULL;
         $data[$priority]['values_array'] = NULL;
       }
       }
-    } 
+    }
     // if mode=select_once then ensure we only select it once
     // if mode=select_once then ensure we only select it once
     if (preg_match('/select_once/', $table_data['mode'])) {
     if (preg_match('/select_once/', $table_data['mode'])) {
       $default_data[$priority]['selected'] = TRUE;
       $default_data[$priority]['selected'] = TRUE;
-      
+
       // save the pkey
       // save the pkey
       if (array_key_exists('primary key', $table_desc)) {
       if (array_key_exists('primary key', $table_desc)) {
         $new_values = array();
         $new_values = array();
-        foreach ($matches[0] as $key => $value) { 
+        foreach ($matches[0] as $key => $value) {
           $new_values[$key] = $value;
           $new_values[$key] = $value;
-        } 
-        $default_data[$priority]['values_default'] = $new_values;   
-      } 
+        }
+        $default_data[$priority]['values_default'] = $new_values;
+      }
     }
     }
   }
   }
+
   return $no_errors;
   return $no_errors;
 }
 }
 
 
@@ -793,7 +799,7 @@ function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field
     }
     }
     else {
     else {
       unset($values[$field]);
       unset($values[$field]);
-    }    
+    }
   }
   }
 
 
   return $values;
   return $values;
@@ -807,7 +813,7 @@ function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field
  * record is looked up and the values array is substituted in.
  * record is looked up and the values array is substituted in.
  *
  *
  */
  */
-function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $data, $record2priority, $nid, 
+function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $data, $record2priority, $nid,
   $priority, $default_data) {
   $priority, $default_data) {
 
 
   // iterate through each field in the $values arrray and
   // iterate through each field in the $values arrray and
@@ -815,16 +821,16 @@ function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $dat
   foreach ($values as $field => $value) {
   foreach ($values as $field => $value) {
     // if the field value is an array then it is an FK
     // if the field value is an array then it is an FK
     if (is_array($value)) {
     if (is_array($value)) {
-      
+
       // get the name and priority of the foreign record
       // get the name and priority of the foreign record
       $foreign_record   = $value['foreign record']['record'];
       $foreign_record   = $value['foreign record']['record'];
       $foreign_priority = $record2priority[$foreign_record];
       $foreign_priority = $record2priority[$foreign_record];
       $foreign_table    = $value['foreign record']['table'];
       $foreign_table    = $value['foreign record']['table'];
       $foreign_field    = $value['foreign record']['field'];
       $foreign_field    = $value['foreign record']['field'];
-      
+
       // get the values of the foreign record and substitute those for the values
       // get the values of the foreign record and substitute those for the values
-      $foreign_values   = $data[$foreign_priority]['values_array'];      
-      
+      $foreign_values   = $data[$foreign_priority]['values_array'];
+
       // check to see if we have any default values in the $default_data array
       // check to see if we have any default values in the $default_data array
       // these were populated from select statements that only need to run once
       // these were populated from select statements that only need to run once
       // so we can reuse the values from those previous selects.
       // so we can reuse the values from those previous selects.
@@ -834,21 +840,21 @@ function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $dat
          $values[$field] = $default_data[$foreign_priority]['values_default'][$foreign_field];
          $values[$field] = $default_data[$foreign_priority]['values_default'][$foreign_field];
          continue;
          continue;
       }
       }
-            
+
       // if the field in the Referral records is in a FK relationship with
       // if the field in the Referral records is in a FK relationship with
       // this field then we can simply keep the value we have
       // this field then we can simply keep the value we have
       $tbl_description = tripal_core_get_chado_table_schema($table_array['table']);
       $tbl_description = tripal_core_get_chado_table_schema($table_array['table']);
       if ($tbl_description and
       if ($tbl_description and
-          array_key_exists('foreign keys', $tbl_description) and 
-          array_key_exists($foreign_table, $tbl_description['foreign keys']) and 
+          array_key_exists('foreign keys', $tbl_description) and
+          array_key_exists($foreign_table, $tbl_description['foreign keys']) and
           array_key_exists($field, $tbl_description['foreign keys'][$foreign_table]['columns']) and
           array_key_exists($field, $tbl_description['foreign keys'][$foreign_table]['columns']) and
           $foreign_field == $tbl_description['foreign keys'][$foreign_table]['columns'][$field]) {
           $foreign_field == $tbl_description['foreign keys'][$foreign_table]['columns'][$field]) {
-         $values[$field] = $foreign_values; 
-      } 
+         $values[$field] = $foreign_values;
+      }
       // if the field in the Referral records is not in an FK relationship
       // if the field in the Referral records is not in an FK relationship
       // with this field then we we have to get the requested value, we must
       // with this field then we we have to get the requested value, we must
       // return only a single value
       // return only a single value
-      else {      
+      else {
         // if the current value of the referral records is a non-array then this
         // if the current value of the referral records is a non-array then this
         // is the primary key, we can use it to select the value we need.
         // is the primary key, we can use it to select the value we need.
         $fk_description = tripal_core_get_chado_table_schema($foreign_table);
         $fk_description = tripal_core_get_chado_table_schema($foreign_table);
@@ -861,7 +867,7 @@ function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $dat
             $record  = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
             $record  = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
             if ($record) {
             if ($record) {
               $values[$field] = $record[0]->$foreign_field;
               $values[$field] = $record[0]->$foreign_field;
-            } 
+            }
             else {
             else {
               unset($values[$field]);
               unset($values[$field]);
             }
             }
@@ -877,17 +883,17 @@ function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $dat
         else {
         else {
           $fvalues  = $foreign_values;
           $fvalues  = $foreign_values;
           $columns = array($foreign_field);
           $columns = array($foreign_field);
-          $options = array('statement_name' => 'blk_' . $nid . $priority . $foreign_table);        
+          $options = array('statement_name' => 'blk_' . $nid . $priority . $foreign_table);
           $record  = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
           $record  = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
           if ($record) {
           if ($record) {
-            $values[$field] = $record[0]->$foreign_field; 
-          } 
+            $values[$field] = $record[0]->$foreign_field;
+          }
           else {
           else {
             unset($values[$field]);
             unset($values[$field]);
           }
           }
-        } // end else from: if (!is_array($foreign_values) ...         
+        } // end else from: if (!is_array($foreign_values) ...
       } // end else from: if ($tbl_description ...
       } // end else from: if ($tbl_description ...
-    } // end if(is_array($value)) ... 
+    } // end if(is_array($value)) ...
   } // end foreach ($values ...
   } // end foreach ($values ...
 
 
   // return the updated field values
   // return the updated field values
@@ -904,8 +910,8 @@ function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $dat
  */
  */
 function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
 function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
 
 
-  if (!array_key_exists('regex_transform', $table_data) or  
-      empty($table_data['regex_transform']) or 
+  if (!array_key_exists('regex_transform', $table_data) or
+      empty($table_data['regex_transform']) or
       !array_key_exists('regex_transform', $table_data) or
       !array_key_exists('regex_transform', $table_data) or
       !is_array($table_data['regex_transform'])) {
       !is_array($table_data['regex_transform'])) {
     return $values;
     return $values;
@@ -914,7 +920,7 @@ function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
   //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
   //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
 
 
   foreach ($table_data['regex_transform'] as $field => $regex_array) {
   foreach ($table_data['regex_transform'] as $field => $regex_array) {
-    if (!array_key_exists('replace', $regex_array) or 
+    if (!array_key_exists('replace', $regex_array) or
         !array_key_exists('pattern', $regex_array) or
         !array_key_exists('pattern', $regex_array) or
         !is_array($regex_array['replace'])) {
         !is_array($regex_array['replace'])) {
       continue;
       continue;
@@ -979,22 +985,22 @@ function tripal_bulk_loader_flatten_array($values) {
  */
  */
 function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
 function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
   $new_bar = FALSE;
   $new_bar = FALSE;
-  $mem = memory_get_usage();       
-  
+  $mem = memory_get_usage();
+
   // First iteration
   // First iteration
   if ($current == 0) {
   if ($current == 0) {
     $new_bar = TRUE;
     $new_bar = TRUE;
     fputs(STDOUT, "Progress:\n");
     fputs(STDOUT, "Progress:\n");
   }
   }
-  
+
   // Percentage round off for a more clean, consistent look
   // Percentage round off for a more clean, consistent look
   $percent = sprintf("%.02f", round(($current/$total) * 100, 2));
   $percent = sprintf("%.02f", round(($current/$total) * 100, 2));
   // percent indicator must be four characters, if shorter, add some spaces
   // percent indicator must be four characters, if shorter, add some spaces
   for ($i = strlen($percent); $i <= 4; $i++) {
   for ($i = strlen($percent); $i <= 4; $i++) {
     $percent = ' ' . $percent;
     $percent = ' ' . $percent;
   }
   }
- 
-  
+
+
   $total_size = $size + $i + 3 + 2;
   $total_size = $size + $i + 3 + 2;
   $place = 0;
   $place = 0;
   // if it's not first go, remove the previous bar
   // if it's not first go, remove the previous bar

+ 4 - 2
tripal_core/api/tripal_core.api.inc

@@ -1402,8 +1402,10 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
       $psql = drupal_substr($psql, 0, -2);  // get rid of the trailing ', '
       $psql = drupal_substr($psql, 0, -2);  // get rid of the trailing ', '
     }
     }
     // finish constructing the prepared SQL statement
     // finish constructing the prepared SQL statement
-    $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
-
+    if ($options['statement_name']) {
+    	$psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
+    }
+    
   } // end if(empty($where)){ } else {
   } // end if(empty($where)){ } else {
 
 
   // if the caller has requested the SQL rather than the results...
   // if the caller has requested the SQL rather than the results...

+ 12 - 1
tripal_stock/tripal_stock.module

@@ -1117,4 +1117,15 @@ function tripal_stock_preprocess_tripal_organism_stocks(&$variables) {
   }
   }
   
   
   $organism->stock_browser =  array('stocks' => $stocks, 'pager' => $pager, 'enabled' => TRUE );
   $organism->stock_browser =  array('stocks' => $stocks, 'pager' => $pager, 'enabled' => TRUE );
-}
+}
+
+/**
+ *
+ *
+ * @ingroup tripal_stock
+ */
+function tripal_stock_preprocess_tripal_stock_base(&$variables) {
+	$stock = $variables['node']->stock;
+	$num_seq = db_result(chado_query("SELECT count(*) FROM feature_stock WHERE stock_id = %d", $stock->stock_id));
+	$stock->num_seq = $num_seq;
+}