Monday, June 04, 2012

SugarCrm 6.3.1: Enhancing Importer - allow importing of related module data

Often when importing data into SugarCrm the built-in importer at a module level is working great. However if you have a need to import data that is actually modeled in SugarCrm as being 2 modules (tables) with a many-many relationship in between then the built-in importer comes up short.

The full patch can be found at the bottom of this posting. This is a non upgradesafe change. Apply at your own risk.

Let us assume that we have the following entity relational model in SugarCrm that has been configured in SugarCrm Studio or in SugarCrm Module Builder.


Module Builder

The Sugar Module Builder enables users to build custom modules from scratch or combine existing or custom objects into a brand new CRM module. Developers can leverage existing Sugar Objects such as Contacts, Accounts, Documents, Cases, and Opportunities to build a new module or create their own custom objects from scratch to form a new module. Users can build an unlimited number of custom modules, which interoperate seamlessly with Reporting, Workflow, and Sugar Studio tools. Upgrades for custom modules are fully supported. Building new modules allows developers to extend Sugar beyond the typical CRM functions and optimize Sugar for any xRM (any Relationship Management) function.

Positive Impacts

  • Create custom modules to track information critical to your business
  • Use pre-defined objects or create custom objects for the new module
  • Share or charge for custom objects on SugarForge and Sugar Exchange.

Sugar Studio

Sugar Studio is the starting place for an administrator to configure the way information is presented in Sugar. Administrators can use Sugar Studio to create and add custom fields, hide fields that are not relevant, and use the extensive customization capabilities of Sugar Logic to create calculated, dependent, and related fields. Sugar Studio is a very simple but powerful WYSIWYG interface that administrators and developers use to configure Sugar to complement a company’s existing business processes.

Positive Impacts

  •  Rearrange the order of fields according to your company’s requirements
  •  Hide fields that are not relevant to your business process
  •  Create and add new custom fields
  •  Calculate variable values based on the value of other fields like opportunity amount or expected close date
  •  Present fields only when necessary using dependent fields


If importing has been enabled for the Skill and the Language module when these modules were created then we can import Skill or Languages as standalone data. The Contact module is a built-in SugarCrm module and it has importing enabled but can also only import contact standalone data. 




There are a few challenges importing related data into SugarCrm:
  1. We need to handle relationships and splitting data into the correct modules.
  2. We need to handle the fact that the id column might not contain the actual id of the data but that another column might do instead.

Without the 2 challenges solved we will not be able to import the below data the way I would prefer.


What we really want in the database after importing the above data is.
  • 2 contacts: John and Jane
  • 3 skills: English literature, European history and PHP
  • 4 languages: English, German, Danish and Swedish 
  • as well as the many-many relations needed so we can recreate the data pictured above

The 2 above mentioned challenges have been solved the following ways:

#1: In the importer step 3 we have added all the "main module's" (Contacts in this case) related modules' fields in the module field dropdown. This way you can map any data  you want into a related module's field.

#2: A primary key field selector has been added on Step 2 in the import if you have selected "Create new records and update existing records" on Step 1 in the importer.




Lets look at the proposed solution.

Step 1: the importer has not been modified visually and looks as below.

(Please note the support for saving an import configuration is working with the new importer functionality).



Step 2: We have added a new field that allows you to select the field that is to be used as "id". It defaults to the standard importer behavior which is using the id column.



Step 3: We have added a marker for the field used as primary id ( purple box below ). Please note the text in the dropdown marked with red boxes. The field selected in the dropdown is prefixex with a module name (<modulename>.<fieldname>) this indicates that it is a field from a related module you want to map to.

As you can see from the screenshot below, the module field dropdown now contains all fields from the main module (Contacts) (main module fields are not prefixed with the module name), as well as the related modules fields (skill_Skill, and lang_Language, these fields are prefixed with the module name).



Note: Do not map any value to a related module's "ID" field. This is handled behind the scenes.


Step 4: No visual changes has happened here



There are quite a few code changes to add this new functionality into the importer and you can see the Subversion patch file below.
Index: include/database/DBHelper.php
===================================================================
--- include/database/DBHelper.php (revision 73)
+++ include/database/DBHelper.php (working copy)
@@ -1185,8 +1185,8 @@
                          $before_value=(float)$bean->fetched_row[$field];
                          $after_value=(float)$bean->$field;
                      } else {
-                         $before_value=$bean->fetched_row[$field];
-                         $after_value=$bean->$field;
+                         $before_value=$bean->fetched_row[$field];   
+                         $after_value=@$bean->$field;
                    }
 
      //Because of bug #25078(sqlserver haven't 'date' type, trim extra "00:00:00" when insert into *_cstm table). so when we read the audit datetime field from sqlserver, we have to replace the extra "00:00:00" again.
Index: modules/Import/Importer.php
===================================================================
--- modules/Import/Importer.php (revision 73)
+++ modules/Import/Importer.php (working copy)
@@ -59,6 +59,7 @@
      */
     private $importColumns;
 
+ private $importRelatedColumns;
     /**
      * @var importSource
      */
@@ -104,9 +105,11 @@
         //Get the default user currency
         $this->defaultUserCurrency = new Currency();
         $this->defaultUserCurrency->retrieve('-99');
-
+        
         //Get our import column definitions
         $this->importColumns = $this->getImportColumns();
+  $this->importRelatedColumns = $this->getRelatedImportColumns();
+
         $this->isUpdateOnly = ( isset($_REQUEST['import_type']) && $_REQUEST['import_type'] == 'update' );
     }
 
@@ -132,7 +135,7 @@
     protected function importRow($row)
     {
         global $sugar_config, $mod_strings;
-
+  global $beanList,$beanFiles;
         $focus = clone $this->bean;
         $focus->unPopulateDefaultValues();
         $focus->save_from_post = false;
@@ -140,6 +143,11 @@
         $this->ifs->createdBeans = array();
         $this->importSource->resetRowErrorCounter();
         $do_save = true;
+        
+        $primary_key = (isset($_REQUEST['primary_key']) && !empty($_REQUEST['primary_key'])) ? $_REQUEST['primary_key'] : false;
+        if(!$primary_key){
+            $primary_key = 'id';
+        }
 
         for ( $fieldNum = 0; $fieldNum < $_REQUEST['columncount']; $fieldNum++ )
         {
@@ -322,46 +330,58 @@
                 return;
             }
         }
-
+        
+        $focus_array = array();
+        $newRecord_array = array();
+        
         // if the id was specified
         $newRecord = true;
-        if ( !empty($focus->id) )
+        if ( !empty($focus->$primary_key) )
         {
-            $focus->id = $this->_convertId($focus->id);
-
+            if($primary_key=='id')
+                $focus->id = $this->_convertId($focus->$primary_key);
             // check if it already exists
-            $query = "SELECT * FROM {$focus->table_name} WHERE id='".$focus->db->quote($focus->id)."'";
+            $join = '';
+            $_def = $focus->getFieldDefinition($primary_key);
+            if($_def['source'] == 'custom_fields') $join = "JOIN {$focus->table_name}_cstm ON id_c = id";
+            $query = "SELECT * FROM {$focus->table_name} $join WHERE $primary_key='".$focus->db->quote($focus->$primary_key)."'";
             $result = $focus->db->query($query)
             or sugar_die("Error selecting sugarbean: ");
 
-            $dbrow = $focus->db->fetchByAssoc($result);
+            while($dbrow = $focus->db->fetchByAssoc($result)){
 
-            if (isset ($dbrow['id']) && $dbrow['id'] != -1)
+                if (isset ($dbrow[$primary_key]) && $dbrow[$primary_key] != -1)
             {
-                // if it exists but was deleted, just remove it
-                if (isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 && $this->isUpdateOnly ==false)
+                    $focus->id = $dbrow['id'];
+                    // if it exists but was deleted, just remove it                                         //skiping deleted rows
+                    if (isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 && $this->isUpdateOnly == false /*&& $primary_key=='id'*/)
                 {
                     $this->removeDeletedBean($focus);
                     $focus->new_with_id = true;
                 }
                 else
                 {
+                        //skiping deleted rows
+                        if(isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 ) continue;
                     if( ! $this->isUpdateOnly )
                     {
-                        $this->importSource->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'],'ID',$focus->id);
+                            $this->importSource->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'],$primary_key,$focus->$primary_key);
                         $this->_undoCreatedBeans($this->ifs->createdBeans);
                         return;
                     }
-
+                        
                     $clonedBean = $this->cloneExistingBean($focus);
                     if($clonedBean === FALSE)
                     {
-                        $this->importSource->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'],'ID',$focus->id);
+                            $this->importSource->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'],$primary_key,$focus->$primary_key);
                         $this->_undoCreatedBeans($this->ifs->createdBeans);
                         return;
                     }
                     else
                     {
+                            $focus_array[] = clone $clonedBean;
+                            $newRecord_array[] = FALSE;
+                            
                         $focus = $clonedBean;
                         $newRecord = FALSE;
                     }
@@ -369,19 +389,100 @@
             }
             else
             {
+                    if($focus->id){
                 $focus->new_with_id = true;
+                    }else{
+                        $focus->new_with_id = false;
+                        $focus_array[] = $this->cloneExistingBean($focus);
+                        $newRecord_array[] = true;
             }
         }
-
+            }
+        }
+        if(count($focus_array)==0){
+            $focus_array[] = $focus;
+            $newRecord_array[] = $newRecord;
+        }
+        for($focus_i=0,$focus_count=count($focus_array);$focus_i<$focus_count;$focus_i++){
+            $focus = $focus_array[$focus_i];
+            $newRecord = $newRecord_array[$focus_i];
         if ($do_save)
         {
             $this->saveImportBean($focus, $newRecord);
+       $mainModuleId = $focus->id;
+       //Save records for related module
+       foreach($this->importRelatedColumns as $k=>$v)
+       {
+         $exploedFields = explode("$",$v);
+         $relatedModule[] =  $exploedFields[0];
+         $relatedModuleField[$exploedFields[0]][] = $exploedFields[1];
+       }
+                if(isset($relatedModule) && is_array($relatedModule))
+       $relatedModules = array_unique($relatedModule);
+                if(isset($relatedModule) && is_array($relatedModule))
+                    foreach($relatedModuleField as $modName => $fldsArr)
+        {
+         $haveValue = 0;
+         $relatedModuleFile = $beanList[$modName];
+         include_once($beanFiles[$relatedModuleFile]);
+         $relatedModuleObj = new $relatedModuleFile();
+         $whereArr = array();
+                        $is_custom = false;
+         foreach($fldsArr as $k=>$fldName)
+         {
+          $fld = $modName."$".$fldName;
+          $fieldNo = array_search($fld,$this->importRelatedColumns);
+          if($row[$fieldNo]!="")
+          {
+           $haveValue++;
+           $relatedModuleObj->$fldName = $row[$fieldNo];
+           $whereArr[] = $fldName ."='". $row[$fieldNo]."'";
+                                if(@$relatedModuleObj->field_defs[$fldName]['source'] == 'custom_fields')  $is_custom = true;
+          }
+         }
+         if($haveValue)
+         {
+          $where = "";
+          $where = implode(" AND ",$whereArr);
+          $sql = "select id from ".$relatedModuleObj->table_name;
+          if($is_custom) $sql .= ' inner join '.$relatedModuleObj->table_name.'_cstm on id=id_c';
+                            $sql .= " where ".$where." and deleted=0";
+                            $result2 = $relatedModuleObj->db->query($sql);
+          $rowQuery = $relatedModuleObj->db->fetchByAssoc($result2);
+          if(count($rowQuery)==0 || empty($rowQuery))
+          {
+           $this->saveImportBean($relatedModuleObj, $newRecord); 
+           $relatedId = $relatedModuleObj->id;
+          }
+          else
+          {
+           $relatedId = $rowQuery['id'];
+          }
+          $rel_table = strtolower($relatedModuleObj->table_name);
+                            $foc_table = strtolower($focus->table_name);
+                            if(strlen($rel_table)>16) $rel_table = substr($rel_table,0,11).substr($rel_table,-5);
+                            if(strlen($foc_table)>16) $foc_table = substr($foc_table,0,11).substr($foc_table,-5);
+                            $rel_field = $foc_table.'_'.$rel_table;
+                            if(!$focus->load_relationship($rel_field)){       
+                                $rel_field = $rel_table.'_'.$foc_table;
+                                if(!$focus->load_relationship($rel_field)){
+                                    $GLOBALS['log']->error("SugarBean.load_relationships, relationship not found.");
+                                    $rel_field = false;
+                                }
+                            }
+                            if($rel_field){
+                                $focus->$rel_field->add($relatedId,array());
+                            }
+                             $focus->save();
+         }
+        }
+                   
             // Update the created/updated counter
             $this->importSource->markRowAsImported($newRecord);
         }
         else
             $this->_undoCreatedBeans($this->ifs->createdBeans);
-
+        }
         unset($defaultRowValue);
 
     }
@@ -544,11 +645,15 @@
         
         $firstrow    = unserialize(base64_decode($_REQUEST['firstrow']));
         $mappingValsArr = $this->importColumns;
-        $mapping_file = new ImportMap();
+        $mappingRelatedArr = $this->importRelatedColumns;
+        $mappArr = $mappingRelatedArr+$mappingValsArr;
+        $mapping_file = new ImportMap();     
+        
+        
         if ( isset($_REQUEST['has_header']) && $_REQUEST['has_header'] == 'on')
         {
             $header_to_field = array ();
-            foreach ($this->importColumns as $pos => $field_name)
+            foreach ($mappArr as $pos => $field_name)
             {
                 if (isset($firstrow[$pos]) && isset($field_name))
                 {
@@ -557,6 +662,8 @@
             }
 
             $mappingValsArr = $header_to_field;
+        }      else{
+         $mappingValsArr =    $mappArr;
         }
         //get array of values to save for duplicate and locale settings
         $advMapping = $this->retrieveAdvancedMapping();
@@ -679,7 +786,26 @@
 
         return $importColumns;
     }
+ protected function getRelatedImportColumns()
+    {
+        $importRelatedColumns = array();
+        foreach ($_REQUEST as $name => $value)
+        {
+            // only look for var names that start with "fieldNum"
+            if (strncasecmp($name, "colnum_", 7) != 0)
+                continue;
 
+            // pull out the column position for this field name
+            $pos = substr($name, 7);
+
+            if ( strpos($value,"$") )
+            {
+                // now mark that we've seen this field
+                $importRelatedColumns[$pos] = $value;
+            }
+        }
+        return $importRelatedColumns;
+    }
     protected function getFieldSanitizer()
     {
         $ifs = new ImportFieldSanitize();
Index: modules/Import/tpls/confirm.tpl
===================================================================
--- modules/Import/tpls/confirm.tpl (revision 73)
+++ modules/Import/tpls/confirm.tpl (working copy)
@@ -170,8 +170,30 @@
         </tr>
         <tr>
             <td colspan="2"><div class="hr" style="margin-top: 0px;"></div></td>
+        </tr>    
+        {if $TYPE != 'import'}
+        <tr>
+            <td colspan="2"><h3>Select primaty field&nbsp;{sugar_help text="It will update the row with the field equal to the value of the csv row"}</h3></td>
         </tr>
         <tr>
+            <td colspan="2">
+                <select name="primary_key">
+                    {foreach from=$SAMPLE_ROWS item=row name=row}
+                        {foreach from=$row item=value}
+                            {if $smarty.foreach.row.first}
+                                {if $HAS_HEADER}
+                                    <option value="{$value}"{if $value|lower == 'id'} selected='selected' {/if}>{$value}</option>
+                                {/if}
+                            {/if}
+                        {/foreach}
+                    {/foreach}
+                </select>
+            </td>
+        </tr>
+        {else}
+            <input name="primary_key" value="" type="hidden" />
+        {/if}                                                                                                 
+        <tr>
             <td colspan="2"><h3>{$MOD.LBL_THIRD_PARTY_CSV_SOURCES}&nbsp;{sugar_help text=$MOD.LBL_THIRD_PARTY_CSV_SOURCES_HELP}</h3></td>
         </tr>
         <tr>
Index: modules/Import/tpls/dupcheck.tpl
===================================================================
--- modules/Import/tpls/dupcheck.tpl (revision 73)
+++ modules/Import/tpls/dupcheck.tpl (working copy)
@@ -84,6 +84,7 @@
 <input type="hidden" id="enabled_dupes" name="enabled_dupes" value="">
 <input type="hidden" id="disabled_dupes" name="disabled_dupes" value="">
 <input type="hidden" id="current_step" name="current_step" value="{$CURRENT_STEP}">
+<input type="hidden" name="primary_key" value="{$primary_field}">
 
    <div class="hr"></div>
     <div>
Index: modules/Import/tpls/step3.tpl
===================================================================
--- modules/Import/tpls/step3.tpl (revision 73)
+++ modules/Import/tpls/step3.tpl (working copy)
@@ -118,10 +118,34 @@
 {/if}
 <tr>
     {if $HAS_HEADER == 'on'}
-    <td id="row_{$smarty.foreach.rows.index}_header">{$item.cell1}</td>
+    <td id="row_{$smarty.foreach.rows.index}_header">
+        {if $primary_field==$item.cell1}
+            <b>{$item.cell1}
+            <small>*Primary Field</small>
+            </b>
+            <input type="hidden" name="primary_key" value="{$primary_field}" id="primary_key" />
+            <script>
+                {literal}
+                (function(obj, evType, fn){ 
+                    if (obj.addEventListener){ 
+                       obj.addEventListener(evType, fn, false); 
+                       return true; 
+                     } else if (obj.attachEvent){ 
+                        var r = obj.attachEvent("on"+evType, fn); 
+                        return r; 
+                     } else { 
+                        return false; 
+                     } 
+                })(window,'load',function(){document.getElementById('primary_key').value=document.getElementById('primary_key_list').value})
+                {/literal}
+            </script>
+        {else}
+            {$item.cell1}
     {/if}
+    </td>
+    {/if}
     <td valign="top" align="left" id="row_{$smarty.foreach.rows.index}_col_0">
-        <select class='fixedwidth' name="colnum_{$smarty.foreach.rows.index}">
+        <select class='fixedwidth' name="colnum_{$smarty.foreach.rows.index}"{if $primary_field==$item.cell1} id="primary_key_list" onblur="document.getElementById('primary_key').value = this.value" {/if}>
             <option value="-1">{$MOD.LBL_DONT_MAP}</option>
             {$item.field_choices}
         </select>
Index: modules/Import/views/view.confirm.php
===================================================================
--- modules/Import/views/view.confirm.php (revision 73)
+++ modules/Import/views/view.confirm.php (working copy)
@@ -63,7 +63,7 @@
         global $sugar_config, $locale;
         
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
-        $this->ss->assign("TYPE",( !empty($_REQUEST['type']) ? $_REQUEST['type'] : "import" ));
+        $this->ss->assign("TYPE",( !empty($_REQUEST['type']) ? $_REQUEST['type'] : ( !empty($_REQUEST['import_type'])?$_REQUEST['import_type'] : "import") ));
         $this->ss->assign("SOURCE_ID", $_REQUEST['source_id']);
 
         $this->instruction = 'LBL_SELECT_PROPERTY_INSTRUCTION';
Index: modules/Import/views/view.dupcheck.php
===================================================================
--- modules/Import/views/view.dupcheck.php (revision 73)
+++ modules/Import/views/view.dupcheck.php (working copy)
@@ -73,6 +73,7 @@
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
         $this->ss->assign("CURRENT_STEP", $this->currentStep);
         $this->ss->assign("JAVASCRIPT", $this->_getJS());
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
 
         $content = $this->ss->fetch('modules/Import/tpls/dupcheck.tpl');
         $this->ss->assign("CONTENT", $content);
Index: modules/Import/views/view.last.php
===================================================================
--- modules/Import/views/view.last.php (revision 73)
+++ modules/Import/views/view.last.php (working copy)
@@ -109,6 +109,8 @@
         $this->ss->assign("errorrecordsFile",ImportCacheFiles::getErrorRecordsWithoutErrorFileName());
         $this->ss->assign("dupeFile",ImportCacheFiles::getDuplicateFileName());
         
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
+        
         if ( $this->bean->object_name == "Prospect" )
         {
          $this->ss->assign("PROSPECTLISTBUTTON", $this->_addToProspectListButton());
Index: modules/Import/views/view.step3.php
===================================================================
--- modules/Import/views/view.step3.php (revision 73)
+++ modules/Import/views/view.step3.php (working copy)
@@ -63,7 +63,7 @@
   public function display()
     {
         global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
-        
+        global $beanList,$beanFiles;
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
         $has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
         $sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
@@ -200,7 +200,91 @@
         if (!empty($importColumns)) {
             $column_sel_from_req = true;
         }
-
+        foreach($this->bean->field_defs as $field)
+        {
+            if(0 == strcmp($field['type'],'link') && (!empty($field['module']) || !empty($field['relationship'])))
+            {
+                if(!empty($field['module']))
+                {
+                    $related_module = $field['module'];
+                }
+                elseif(!empty($field['relationship']))
+                {
+                    require_once("data/Relationships/RelationshipFactory.php");
+                    $test = SugarRelationshipFactory::getInstance()->getRelationship($field['relationship']);
+                    if($test->def['relationships'][$field['relationship']]['lhs_module'] == $this->bean->module_dir)
+                    {
+                        $relatedMods[] = $test->def['relationships'][$field['relationship']]['rhs_module'];
+                    }
+                    else
+                    {
+                        $relatedMods[] = $test->def['relationships'][$field['relationship']]['lhs_module'];
+                    }
+                }
+            }
+        }
+        //add extra related fields
+        foreach($relatedMods as $key=>$relatedModule)
+        {
+                if(array_key_exists($relatedModule,$beanList))
+                {
+                $relatedModuleFile = $beanList[$relatedModule];
+                include_once($beanFiles[$relatedModuleFile]);
+                $relatedModuleObj = new $relatedModuleFile();
+                $fieldsRel  = $relatedModuleObj->get_importable_fields();
+                $relModuleStrings = return_module_language($current_language, $relatedModuleObj->module_dir);
+                foreach ( $fieldsRel as $fieldname => $properties ) {
+                    if($properties['relationship'])
+                    continue;
+                    // get field name
+                    if (!empty($relModuleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
+                    {
+                         $displayname = str_replace(":","", $relModuleStrings['LBL_EXPORT_'.strtoupper($fieldname)] );
+                    }
+                    else if (!empty ($properties['vname']))
+                    {
+                        $displayname = str_replace(":","",translate($properties['vname'] ,$relatedModuleObj->module_dir));
+                    }
+                    else
+                        $displayname = str_replace(":","",translate($properties['name'] ,$relatedModuleObj->module_dir));
+                    
+                    $selected = '';   
+                    if ($column_sel_from_req && isset($importColumns[$field_count])) {
+                        if ($fieldname == $importColumns[$field_count]) {
+                            //$selected = ' selected="selected" ';
+                            $defaultField = $fieldname;
+                            $mappedFields[] = $fieldname;
+                        }
+                    } else {
+                        if ( !empty($defaultValue) && !in_array($fieldname,$mappedFields)
+                                                        && !in_array($fieldname,$ignored_fields) )
+                        {
+                            if ( strtolower($fieldname) == strtolower($defaultValue)
+                                || strtolower($fieldname) == str_replace(" ","_",strtolower($defaultValue))
+                                || strtolower($displayname) == strtolower($defaultValue)
+                                || strtolower($displayname) == str_replace(" ","_",strtolower($defaultValue)) )
+                            {
+                                //$selected = ' selected="selected" ';
+                                $defaultField = $fieldname;
+                                $mappedFields[] = $fieldname;
+                            }
+                        }
+                    }  
+                    // get field type information
+                    $fieldtype = '';
+                    if ( isset($properties['type'])
+                            && isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
+                        $fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
+                    if ( isset($properties['comment']) )
+                        $fieldtype .= ' - ' . $properties['comment'];
+                        
+                    $optionsRelated[$relatedModuleObj->module_dir.'$'.$fieldname] = '<option value="'.$relatedModuleObj->module_dir.'$'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
+                        . $selected . $req_class . '>'. $relatedModuleObj->module_dir.".". $displayname . '</option>\n';
+                }
+                
+                }
+        }
+        
         for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
             // See if we have any field map matches
             $defaultValue = "";
@@ -225,7 +309,17 @@
             $defaultField = '';
             global $current_language;
       $moduleStrings = return_module_language($current_language, $this->bean->module_dir);
+            
+            $related_options_clone = $optionsRelated;
 
+            if(
+                isset($firstrow_name) &&
+                isset($field_map[$firstrow_name]) &&
+                isset($related_options_clone[$field_map[$firstrow_name]])
+            ){
+                $related_options_clone[$field_map[$firstrow_name]] = str_replace('<option ','<option selected="selected" ',$related_options_clone[$field_map[$firstrow_name]]);
+            }
+            
             foreach ( $fields as $fieldname => $properties ) {
                 // get field name
                 if (!empty($moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
@@ -278,7 +372,6 @@
                 $options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
                     . $selected . $req_class . '>' . $displayname . $req_mark . '</option>\n';
             }
-
             // get default field value
             $defaultFieldHTML = '';
             if ( !empty($defaultField) ) {
@@ -306,6 +399,11 @@
             $cellOneData = isset($rows[0][$field_count]) ? $rows[0][$field_count] : '';
             $cellTwoData = isset($rows[1][$field_count]) ? $rows[1][$field_count] : '';
             $cellThreeData = isset($rows[2][$field_count]) ? $rows[2][$field_count] : '';
+            
+            if(count($optionsRelated)>0 && @$_REQUEST['primary_key'] != $firstrow_name)
+            {
+                $options = array_merge($options, $related_options_clone);
+            }
             $columns[] = array(
                 'field_choices' => implode('',$options),
                 'default_field' => $defaultFieldHTML,
@@ -382,6 +480,7 @@
 
         $this->ss->assign("COLUMNCOUNT",$ret_field_count);
         $this->ss->assign("rows",$columns);
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
 
         $this->ss->assign('datetimeformat', $GLOBALS['timedate']->get_cal_date_time_format());
 
@@ -768,4 +867,4 @@
 
 EOJAVASCRIPT;
     }
-}
+}
\ No newline at end of file

11 comments:

Anonymous said...

Hello there,

Just thought I should point out you got some replies to this on the Sugar forums: http://forums.sugarcrm.com/f3/solved-importing-related-module-data-sugarcrm-importer-sugarcrm-6-3-1-patch-80503/

Anonymous said...

Hi,
Could you create article on how to hide field from certain users?
For example: Module cases and field status, user: aaa.
It's hard to find this think fully explained. Thank you in advance.

Kenneth Thorman said...

Hi Adam

I am a bit short on time at the moment, so I do not think I will have time to move this to Github in the near future.

Regards
Kenneth

Kenneth Thorman said...

Hi Anonymous

I have actually already implemented this as an core feature in SugarCrm in 5.1.0b, but am in the progress of moving this to SugarCrm 6.4.2.

Full support / builtin under Admin/Roles to on each field for a role either show the field, make it readonly or completely hide it.

I will see if I have time to create a post about that here.

Regards
Kenneth

Anonymous said...

Well, I hope you will :)
While changing privileges to listview is quite easy task to modify files, changing that in detail or edit view is unfortunately completely different.

Gary Cole said...

I like Your Post very much about SugarCRM Development. The Post is very helpful and useful for me. Thanks for share this valuable Information.

Jason Eggers said...

Definitely one of the coolest customizations I've seen for SugarCRM. Can't believe I haven't found your blog before. What do you think are the limitations to getting support for this feature into the core product? I know you're busy but doing a pull request into the sugarcrm_dev branch would be awesome: https://github.com/sugarcrm/sugarcrm_dev

Kenneth Thorman said...

Hi Jason

The sugar core team contacted me about this feature, since they were interested in incorporating this in the official releases. I told them that I did not have time to port this to the most current release at the time (which was 6.4.2). But that they were welcome to take the patch and apply it and merge formward.

The last thing I heard was that they were working on it.

Regards
Kenneth

sumit sahay said...

Hi Kenneth,

I am have query, I want to add some fields in the the View Import File Properties Page.

In the Step:2 while Importing the record, there is one button in the page named as"View Import File Properties", If someone click the button then some field are there, I want to add some fields there.I went through the file(modules/Import/tpls/confirm.tpl) and (modules/Import/view/view.confirm.php)checked in the instance, but didn't get success. What I need to do. How to add the fields there.

Lane Best said...

SugarCrm importer at a module stage performs well. However If I need to transfer information that is actually patterned in SugarCrm as being 2 segments with a many connection in between then the built-in importer comes up brief.

SugarCRM Customization said...

Your article has proven useful to me. It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content.