2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 require_once("include/EditView/EditView2.php");
39 require_once("include/upload_file.php");
41 class ViewConvertLead extends SugarView
43 protected $fileName = "modules/Leads/metadata/convertdefs.php";
44 protected $new_contact = false;
46 public function __construct(
48 $view_object_map = array()
51 parent::SugarView($bean, $view_object_map);
52 $this->medataDataFile = $this->fileName;
53 if (file_exists("custom/$this->fileName"))
55 $this->medataDataFile = "custom/$this->fileName";
59 public function preDisplay()
61 if (!$this->bean->ACLAccess('edit')) {
62 ACLController::displayNoAccess();
68 * @see SugarView::display()
70 public function display()
72 if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
74 return $this->handleSave();
79 // get the EditView defs to check if opportunity_name exists, for a check below for populating data
80 $opportunityNameInLayout = false;
81 $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
82 $this->medataDataFile = $editviewFile;
83 if (file_exists("custom/{$editviewFile}"))
85 $this->medataDataFile = "custom/{$editviewFile}";
87 include($this->medataDataFile);
88 foreach($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section){
89 foreach($section as $row_array){
90 foreach($row_array as $cell){
91 if(isset($cell['name']) && $cell['name'] == 'opportunity_name'){
92 $opportunityNameInLayout = true;
98 $this->medataDataFile = $this->fileName;
99 if (file_exists("custom/$this->fileName"))
101 $this->medataDataFile = "custom/$this->fileName";
105 $this->checkForDuplicates($this->focus);
106 $smarty = new Sugar_Smarty();
107 $ev = new EditView();
109 $ev->view = "ConvertLead";
110 echo $this->getModuleTitle();
112 require_once("include/QuickSearchDefaults.php");
113 $qsd = QuickSearchDefaults::getQuickSearchDefaults();
114 $qsd->setFormName("ConvertLead");
116 $this->contact = new Contact();
117 // Bug #50126 We have to fill account_name & add ability to select account from popup with pre populated name
118 if (!empty($this->focus->account_name))
120 $smarty->assign('displayParams', array(
121 'initial_filter' => '&name_advanced=' . urlencode($this->focus->account_name))
125 $relatedFields = $this->contact->get_related_fields();
126 $selectFields = array();
127 foreach ($this->defs as $moduleName => $mDefs)
129 if (!empty($mDefs[$ev->view]['select']) && !empty($relatedFields[$mDefs[$ev->view]['select']]))
131 $selectFields[$moduleName] = $mDefs[$ev->view]['select'];
134 foreach ($relatedFields as $fDef)
136 if (!empty($fDef['link']) && !empty($fDef['module']) && $fDef['module'] == $moduleName)
138 $selectFields[$moduleName] = $fDef['name'];
143 $smarty->assign('selectFields', $selectFields);
145 $smarty->assign("contact_def", $this->contact->field_defs);
146 $smarty->assign("form_name", "ConvertLead");
147 $smarty->assign("form_id", "ConvertLead");
148 $smarty->assign("module", "Leads");
149 $smarty->assign("view", "convertlead");
150 $smarty->assign("bean", $this->focus);
151 $smarty->assign("record_id", $this->focus->id);
153 $smarty->assign('MOD', $mod_strings);
154 $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
156 echo "<div class='edit view' style='width:auto;'>";
158 global $sugar_config, $app_list_strings, $app_strings;
159 $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
161 //Switch up list depending on copy or move
162 if($sugar_config['lead_conv_activity_opt'] == 'move')
164 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('None'=>$app_strings['LBL_NONE'], 'Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
166 else if($sugar_config['lead_conv_activity_opt'] == 'copy')
168 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
173 foreach($this->defs as $module => $vdef)
175 if(!isset($beanList[$module]))
181 $bean = $beanList[$module];
182 $focus = new $bean();
184 // skip if we aren't allowed to save this bean
185 if (!$focus->ACLAccess('save'))
190 $focus->fill_in_additional_detail_fields();
191 foreach($focus->field_defs as $field => $def)
193 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
195 if ($module == "Accounts" && $field == 'name')
197 $focus->name = $this->focus->account_name;
199 else if ($module == "Opportunities" && $field == 'amount')
201 $focus->amount = unformat_number($this->focus->opportunity_amount);
203 else if ($module == "Opportunities" && $field == 'name') {
204 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
205 $focus->name = $this->focus->opportunity_name;
208 else if ($field == "id")
210 //If it is not a contact, don't copy the ID from the lead
211 if ($module == "Contacts") {
212 $focus->$field = $this->focus->$field;
214 } else if (is_a($focus, "Company") && $field == 'phone_office')
216 //Special case where company and person have the same field with a different name
217 $focus->phone_office = $this->focus->phone_work;
219 else if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
221 $tmp_field = str_replace("billing_", "primary_", $field);
222 $focus->field_defs[$field]["type"] = "text";
223 if (isset($this->focus->$tmp_field)) {
224 $focus->$field = $this->focus->$tmp_field;
228 else if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
230 $tmp_field = str_replace("shipping_", "primary_", $field);
231 if (isset($this->focus->$tmp_field)) {
232 $focus->$field = $this->focus->$tmp_field;
234 $focus->field_defs[$field]["type"] = "text";
236 else if (isset($this->focus->$field))
238 $focus->$field = $this->focus->$field;
243 //Copy over email data
244 $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
246 echo($ev->display(false));
247 echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
250 echo ($qsd->getQSScriptsJSONAlreadyDefined());
251 // need to re-assign bean as it gets overridden by $ev->display
252 $smarty->assign("bean", $this->focus);
253 $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
256 protected function getRecord()
258 $this->focus = new Lead();
259 if (isset($_REQUEST['record']))
261 $this->focus->retrieve($_REQUEST['record']);
265 protected function loadDefs()
268 include($this->medataDataFile);
269 $this->defs = $viewdefs;
273 * Returns the javascript to enable/disable validation of each module's sub-form
274 * //TODO: This should probably be on the smarty template
275 * @param $module String the target module name.
276 * @param $focus SugarBean instance of the target module.
277 * @param $focus EditView def for the module.
278 * @return String, javascript to echo to page.
280 protected function getValidationJS(
286 $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
288 <script type='text/javascript'>
289 if (!SUGAR.convert) SUGAR.convert = {requiredFields: {}};
290 SUGAR.convert.toggle$module = function(){
292 inputsWithErrors = [];
293 if(!SUGAR.convert.{$module}Enabled)
295 for(var i in SUGAR.convert.requiredFields.$module)
297 addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
300 if ($validateSelect) {
302 removeFromValidate('ConvertLead', '{$viewdef['select']}');";
306 SUGAR.convert.{$module}Enabled = true;
308 for(var i in SUGAR.convert.requiredFields.$module)
310 removeFromValidate('ConvertLead', '$module' + i);
312 if ($validateSelect) {
314 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
315 . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
318 SUGAR.convert.{$module}Enabled = false;
320 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
323 if (isset($viewdef['required']) && $viewdef['required'])
325 if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
328 SUGAR.convert.{$module}Enabled = true;";
331 YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
332 } else if (isset($viewdef['default_action']) && $viewdef['default_action'] == "create")
334 $jsOut .= "\n SUGAR.convert.{$module}Enabled = true;";
337 YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
338 SUGAR.convert.requiredFields.$module = {};";
339 foreach($focus->field_defs as $field => $def)
341 if (isset($def['required']) && $def['required'])
344 SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
355 * Saves a new Contact as well as any related items passed in.
359 protected function handleSave()
361 require_once('modules/Campaigns/utils.php');
362 require_once("include/formbase.php");
364 if (!empty($_REQUEST['record']))
367 $lead->retrieve($_REQUEST['record']);
373 $selectedBeans = array();
375 //Make sure the contact object is availible for relationships.
376 $beans['Contacts'] = new Contact();
377 $beans['Contacts']->id = create_guid();
378 $beans['Contacts']->new_with_id = true;
380 // Bug 39287 - Check for Duplicates on selected modules before save
381 if (!empty($_REQUEST['selectedContact']))
383 $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
384 if (!empty($beans['Contacts']->id))
386 $beans['Contacts']->new_with_id = false;
387 unset($_REQUEST["convert_create_Contacts"]);
388 unset($_POST["convert_create_Contacts"]);
391 elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact']))
393 require_once('modules/Contacts/ContactFormBase.php');
394 $contactForm = new ContactFormBase();
395 $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
397 if (isset($duplicateContacts))
399 echo $contactForm->buildTableForm($duplicateContacts, 'Contacts');
402 $this->new_contact = true;
403 } elseif (isset($_POST['ContinueContact'])) {
404 $this->new_contact = true;
406 if (!empty($_REQUEST['selectedAccount']))
408 $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
409 unset($_REQUEST["convert_create_Accounts"]);
410 unset($_POST["convert_create_Accounts"]);
412 elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount']))
414 require_once('modules/Accounts/AccountFormBase.php');
415 $accountForm = new AccountFormBase();
416 $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
417 if (isset($duplicateAccounts))
419 echo $accountForm->buildTableForm($duplicateAccounts);
424 foreach ($this->defs as $module => $vdef)
426 //Create a new record if "create" was selected
427 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
429 //Save the new record
430 $bean = $beanList[$module];
431 if (empty($beans[$module]))
432 $beans[$module] = new $bean();
434 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
436 // when creating a new contact, do not populate it with lead's old account_id
437 if ($module == 'Contacts') {
438 $beans[$module]->account_id = '';
441 //If an existing bean was selected, relate it to the contact
442 else if (!empty($vdef['ConvertLead']['select']))
444 //Save the new record
445 $select = $vdef['ConvertLead']['select'];
446 $fieldDef = $beans['Contacts']->field_defs[$select];
447 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
449 $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
450 $selects[$module] = $_REQUEST[$fieldDef['id_name']];
451 if (!empty($_REQUEST[$select]))
453 $beans['Contacts']->$select = $_REQUEST[$select];
455 // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
456 $bean = loadBean($module);
457 $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
458 $selectedBeans[$module] = $bean;
463 $this->handleActivities($lead, $beans);
464 // Bug 39268 - Add the lead's activities to the selected beans
465 $this->handleActivities($lead, $selectedBeans);
467 //link selected account to lead if it exists
468 if (!empty($selectedBeans['Accounts']))
470 $lead->account_id = $selectedBeans['Accounts']->id;
473 //Handle non-contacts relationships
474 foreach ($beans as $bean)
478 if (empty($bean->assigned_user_id))
480 $bean->assigned_user_id = $lead->assigned_user_id;
482 $leadsRel = $this->findRelationship($bean, $lead);
483 if (!empty($leadsRel))
485 $bean->load_relationship($leadsRel);
486 $relObject = $bean->$leadsRel->getRelationshipObject();
487 if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
489 $id_field = $relObject->rhs_key;
490 $lead->$id_field = $bean->id;
494 $bean->$leadsRel->add($lead->id);
498 //Special case code for opportunities->Accounts
499 if ($bean->object_name == "Opportunity" && empty($bean->account_id))
501 if (isset($beans['Accounts']))
503 $bean->account_id = $beans['Accounts']->id;
504 $bean->account_name = $beans['Accounts']->name;
506 else if (!empty($selects['Accounts']))
508 $bean->account_id = $selects['Accounts'];
512 //create meetings-users relationship
513 if ($bean->object_name == "Meeting")
515 $bean = $this->setMeetingsUsersRelationship($bean);
517 $this->copyAddressFields($bean, $beans['Contacts']);
520 //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522
521 if (isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact")
523 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
527 { //Mark the original Lead converted
528 $lead->status = "Converted";
529 $lead->converted = '1';
530 $lead->in_workflow = true;
534 $this->displaySaveResults($beans);
537 public function setMeetingsUsersRelationship($bean)
539 global $current_user;
540 $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
541 if (!empty($meetingsRel))
543 $bean->load_relationship($meetingsRel);
544 $bean->$meetingsRel->add($current_user->id);
552 protected function displaySaveResults(
558 foreach($beans as $bean)
560 $beanName = $bean->object_name;
561 if ( $beanName == 'Contact' && !$this->new_contact ) {
562 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
563 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
564 {$bean->get_summary_text()}
568 global $app_list_strings;
569 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
570 $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
572 $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
574 if(empty($module_name)) {
575 $module_name = translate($beanName);
577 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
578 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
579 {$bean->get_summary_text()}
587 protected function handleActivities(
592 global $app_list_strings;
593 global $sugar_config;
595 $parent_types = $app_list_strings['record_type_display'];
597 $activities = $this->getActivitiesFromLead($lead);
599 //if account is being created, we will specify the account as the parent bean
600 $accountParentInfo = array();
602 //determine the account id info ahead of time if it is being created as part of this conversion
603 if(!empty($beans['Accounts'])){
604 $account_id = create_guid();
605 if(!empty($beans['Accounts']->id)){
606 $account_id = $beans['Accounts']->id;
608 $beans['Accounts']->id = $account_id;
610 $accountParentInfo = array('id'=>$account_id,'type'=>'Accounts');
613 foreach($beans as $module => $bean)
615 if (isset($parent_types[$module]))
617 if (empty($bean->id))
619 $bean->id = create_guid();
620 $bean->new_with_id = true;
622 if( isset($_POST['lead_conv_ac_op_sel']) && $_POST['lead_conv_ac_op_sel'] != 'None')
624 foreach($activities as $activity)
626 if (!isset($sugar_config['lead_conv_activity_opt']) || $sugar_config['lead_conv_activity_opt'] == 'copy') {
627 if (isset($_POST['lead_conv_ac_op_sel'])) {
628 //if the copy to module(s) are defined, copy only to those module(s)
629 if (is_array($_POST['lead_conv_ac_op_sel'])) {
630 foreach ($_POST['lead_conv_ac_op_sel'] as $mod) {
631 if ($mod == $module) {
632 $this->copyActivityAndRelateToBean($activity, $bean, $accountParentInfo);
639 else if ($sugar_config['lead_conv_activity_opt'] == 'move') {
640 // if to move activities, should be only one module selected
641 if ($_POST['lead_conv_ac_op_sel'] == $module) {
642 $this->moveActivity($activity, $bean);
652 * Change the parent id and parent type of an activity
653 * @param $activity Activity to be modified
654 * @param $bean New parent bean of the activity
656 protected function moveActivity($activity, $bean) {
660 if (!empty($_REQUEST['record']))
663 $lead->retrieve($_REQUEST['record']);
666 // delete the old relationship to the old parent (lead)
667 if ($rel = $this->findRelationship($activity, $lead)) {
668 $activity->load_relationship ($rel) ;
670 if ($activity->parent_id && $activity->id) {
671 $activity->$rel->delete($activity->id, $activity->parent_id);
675 // add the new relationship to the new parent (contact, account, etc)
676 if ($rel = $this->findRelationship($activity, $bean)) {
677 $activity->load_relationship ($rel) ;
679 $relObj = $activity->$rel->getRelationshipObject();
680 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
682 $key = $relObj->rhs_key;
683 $activity->$key = $bean->id;
685 $activity->$rel->add($bean);
688 // set the new parent id and type
689 $activity->parent_id = $bean->id;
690 $activity->parent_type = $bean->module_dir;
696 * Gets the list of activities related to the lead
697 * @param Lead $lead Lead to get activities from
698 * @return Array of Activity SugarBeans .
700 protected function getActivitiesFromLead(
706 global $beanList, $db;
708 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
709 $activities = array();
711 foreach($activitesList as $module)
713 $beanName = $beanList[$module];
714 $activity = new $beanName();
715 $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
716 $result = $db->query($query,true);
717 while($row = $db->fetchByAssoc($result))
719 $activity = new $beanName();
720 $activity->retrieve($row['id']);
721 $activity->fixUpFormatting();
722 $activities[] = $activity;
729 protected function copyActivityAndRelateToBean(
737 $newActivity = clone $activity;
738 $newActivity->id = create_guid();
739 $newActivity->new_with_id = true;
741 //set the parent id and type if it was passed in, otherwise use blank to wipe it out
744 if(!empty($parentArr)){
745 if(!empty($parentArr['id'])){
746 $parentID = $parentArr['id'];
749 if(!empty($parentArr['type'])){
750 $parentType = $parentArr['type'];
755 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
756 if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
758 $newActivity->contact_id = $newActivity->contact_name = "";
761 if ($rel = $this->findRelationship($newActivity, $bean))
763 if (isset($newActivity->$rel))
765 // this comes form $activity, get rid of it and load our own
766 $newActivity->$rel = '';
769 $newActivity->load_relationship ($rel) ;
770 $relObj = $newActivity->$rel->getRelationshipObject();
771 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
773 $key = $relObj->rhs_key;
774 $newActivity->$key = $bean->id;
777 //parent (related to field) should be blank unless it is explicitly sent in
778 //it is not sent in unless the account is being created as well during lead conversion
779 $newActivity->parent_id = $parentID;
780 $newActivity->parent_type = $parentType;
782 $newActivity->update_date_modified = false; //bug 41747
783 $newActivity->save();
784 $newActivity->$rel->add($bean);
785 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
786 UploadFile::duplicate_file($activity->id, $newActivity->id, $newActivity->filename);
792 * Populates the passed in Bean fron the contact and the $_REQUEST
793 * @param String $module Module of new bean
794 * @param SugarBean $bean SugarBean to be populated.
795 * @param Contact $contact Contact to relate the bean to.
797 protected function populateNewBean(
804 populateFromPost($module, $bean, true);
806 //Copy data from the contact to new bean
807 foreach($bean->field_defs as $field => $def)
809 if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
811 $bean->$field = $lead->$field;
812 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
815 //Try to link to the new contact
817 if (!empty($vdef['ConvertLead']['select']))
819 $select = $vdef['ConvertLead']['select'];
820 $fieldDef = $contact->field_defs[$select];
821 if (!empty($fieldDef['id_name']))
823 $bean->id = create_guid();
824 $bean->new_with_id = true;
825 $contact->$fieldDef['id_name'] = $bean->id ;
826 if ($fieldDef['id_name'] != $select) {
827 $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
828 if (!empty($rname) && isset($bean->$rname))
829 $contact->$select = $bean->$rname;
831 $contact->$select = $bean->name;
834 } else if ($module != "Contacts"){
835 $contactRel = $this->findRelationship($contact, $bean);
836 if (!empty($contactRel))
838 $bean->id = create_guid();
839 $bean->new_with_id = true;
840 $contact->load_relationship ($contactRel) ;
841 $relObject = $contact->$contactRel->getRelationshipObject();
842 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
844 $id_field = $relObject->rhs_key;
845 $bean->$id_field = $contact->id;
847 $contact->$contactRel->add($bean);
849 //Set the parent of activites to the new Contact
850 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
852 $bean->parent_id = $contact->id;
853 $bean->parent_type = "Contacts";
859 protected function copyAddressFields($bean, $contact)
861 //Copy over address info from the contact to any beans with address not set
862 foreach($bean->field_defs as $field => $def)
864 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
867 if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
871 if(strpos($field, "_address_street_2") !== false)
872 $type = "_address_street_2";
873 else if(strpos($field, "_address_street_3") !== false)
874 $type = "_address_street_3";
875 else if(strpos($field, "_address_street_4") !== false)
877 else if(strpos($field, "_address_street") !== false)
878 $type = "_address_street";
879 else if(strpos($field, "_address_city") !== false)
880 $type = "_address_city";
881 else if(strpos($field, "_address_state") !== false)
882 $type = "_address_state";
883 else if(strpos($field, "_address_postalcode") !== false)
884 $type = "_address_postalcode";
885 else if(strpos($field, "_address_country") !== false)
886 $type = "_address_country";
889 if (isset($contact->$var))
890 $bean->$field = $contact->$var;
896 protected function findRelationship(
902 require_once("modules/TableDictionary.php");
903 foreach ($from->field_defs as $field=>$def)
905 if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship']))
907 $rel_name = $def['relationship'];
909 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
911 $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
913 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
915 $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
917 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
918 && isset($dictionary[$rel_name]['relationships'][$rel_name]))
920 $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
922 if (!empty($rel_def)) {
923 if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
927 else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
937 protected function findRelationshipByName($from, $rel_name)
940 require_once("modules/TableDictionary.php");
941 foreach ($from->field_defs as $field => $def)
943 if (isset($def['relationship']) && $def['relationship'] == $rel_name)
951 * @see SugarView::_getModuleTitleParams()
953 protected function _getModuleTitleParams($browserTitle = false)
956 $params = parent::_getModuleTitleParams($browserTitle);
957 $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
958 $params[] = $mod_strings['LBL_CONVERTLEAD'];
963 protected function checkForDuplicates(
967 if ($lead->status == "Converted")
969 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
971 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
972 $result = $lead->db->query($q);
973 while($row = $lead->db->fetchByAssoc($result)) {
974 $contact = new Contact();
975 $contact->retrieve($row['id']);
976 $dupes[$row['id']] = $contact->name;
980 foreach($dupes as $id => $name)
982 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");