function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
VRKVRK 

custom clone button issues

Hi
i am having issues with Custom Clone button , can anyone pls check and  help on this .
Issue :
When click on Custom Clone Button , open popup page and close WITHOUT modify any fields on the popup page.
When refresh page, duplicate record is created .

Issue Replication steps:
Navigate to any opportunity record page and click on Custom Clone Button 
ii. Then open popup window with existing record Values
iii. click on Cancel Button ( Not selecting Save Record)
iv. Refresh page, then duplicate opporunity record created.

code:
comp:
<aura:component controller="NYL_CloneDeal"  implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordId" type="Id" /> 
                  
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
</aura:component>

Controller:
({
     doInit : function(component, event, helper) {
        var action = component.get("c.cloneDealWithTeam");
        action.setParams({ "DealID": component.get("v.recordId")});
        action.setCallback( this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();  
                 if(result.includes('error')){               /// display error message 
                   alert(result); 
                    return false;
                     
                }  
                    window.open(window.location.origin + '/' + result + '/e?retURL=' + result,'_self');
               
                var dismissActionPanel = $A.get("e.force:closeQuickAction");
                dismissActionPanel.fire();
            }
        });
        $A.enqueueAction(action);
    },
})


Apex class:

@AuraEnabled
  webservice static String cloneDealWithTeam(String DealID) {
    Boolean roleOriginator1 = false;
    Boolean mcfRoleOriginator1 = false;
    Integer iterationNumber = -1;
    Integer mcfIterationNumber = -1;
    Integer index;
    Integer mcfIndex;
    Opportunity clonedOppty;
    
    try {
        Set<String> fieldsToBeCloned = new Set<String>{'issuer_account__c','est_total_lien_leverage__c','investment_bank__c', 
                                                       'project_name__c', 'description', 'deal_category__c',
                                                       'accountid', 'classification__c', 'alternate_senior_leverage__c', 'alternate_total_leverage__c', 'junior_debt_pricing__c'};
      String objectName = 'Opportunity';
      String query = 'SELECT';
      String oppId = DealID;
            
      //be carefull here... you might hit heap size issues if there are too many fields on the object
      Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
           
      // Grab the fields from the describe method and append them to the queryString one by one.
      for(String s : objectFields.keySet()) {
        
        if (fieldsToBeCloned.contains(s)) //Only copy certain fields not all as per: T-550675
          query += ' ' + s + ',';
      }


      //strip off the last comma
      query = query.removeEnd (',');
            
      // Add FROM statement
      query += ' FROM ' + objectName;
            
      // Add on a WHERE/ORDER/LIMIT statement as needed
      query += ' WHERE ID = :oppId';
      Opportunity oldOppty = database.query(query);
      
      clonedOppty = oldOppty.clone(false, true, false, false);
      System.debug(clonedOppty.Id+'cloned Opty:'+clonedOppty);
    
        clonedOppty.OwnerId = UserInfo.getUserId();
         try {
          insert clonedOppty;
        } catch (DMLException ex) { 
          System.debug(ex.getMessage());
          return 'Error:'+ex.getMessage();
        }
         
        if (clonedOppty.ID != null) {
          
            List<Deal_Team__c> mcfDealTeam =  getMCFDealTeam(DealID);
            mcfDealTeam = mcfDealTeam.DeepClone(false,false,false);
            
            List<OpportunityTeamMember> opptyTeam = getOpportunityTeam(DealID);
            opptyTeam = opptyTeam.DeepClone(false,false,false);
            for (OpportunityTeamMember teamMember : opptyTeam) {
                iterationNumber = iterationNumber + 1;
                
                if(teamMember.TeamMemberRole == 'Originator 1'){
                  roleOriginator1 = true;
                  index = iterationNumber;
                }
                else{
                  teamMember.OpportunityID = clonedOppty.ID;
                }
                
            }
            System.debug('roleOriginator:'+roleOriginator1);
            System.debug('OTM1:'+opptyTeam);
            if(roleOriginator1){
              opptyTeam.remove(index);
              OpportunityTeamMember otm = new OpportunityTeamMember();
              otm.OpportunityID = clonedOppty.ID;
              otm.TeamMemberRole = 'Originator 1';
              otm.userId = UserInfo.getUserId();
              opptyTeam.add(otm);
              System.debug('OTM2:'+opptyTeam);
            }
            
            if(!roleOriginator1){
              
              OpportunityTeamMember otm = new OpportunityTeamMember();
              
              otm.OpportunityID = clonedOppty.ID;
              otm.TeamMemberRole = 'Originator 1';
              otm.userId = UserInfo.getUserId();
              
              opptyTeam.add(otm);
              System.debug('OTM3:'+opptyTeam);
            }
            
            
            try {
              insert opptyTeam;
              insert mcfDealTeam;
            } catch (DMLException ex) {
              System.debug('****1****'+ex.getMessage()+'*****Line Number:'+ex.getLineNumber());

              return 'Error:' + ex.getMessage();
            }
            
        }
     
      
    } catch (Exception e){
      System.debug('*****2***'+e.getMessage());
        return 'Error: ' + e.getMessage();
    }

    System.debug('****3****'+clonedOppty.ID);

    return clonedOppty.ID;
  }
  
Thanks
VRK
 
SwethaSwetha (Salesforce Developers) 
HI VRK,
What does it show in the debug logs for  System.debug(clonedOppty.Id+'cloned Opty:'+clonedOppty);  Also, the code does not have any mention about the Cancel functionality?Can you check if ther is any other piece of code? Thanks