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
Ravi@2018Ravi@2018 

Move opportunity related list from duplicate account to newly update Account using triggers

I am trying to move opportunity related lsit from duplicate account to other account when a record is update with duplicate Account Name.Here i.e I have two records A and B so when i update name of Account "B" as "A" all opportunity relatedlist data should be moved from Old record A to newly updated record.
Here is my trigger everything look good but trigger is not working can anyone help me find the issue...

trigger MerageAccOpp on Account (after update) {

    if (trigger.isUpdate){
    
        List<Account> lst_acc;
        List<Opportunity> lst_opp;
        String nameaccount;
        Account a;
        for (Account accnew : Trigger.new){
            system.debug('Enetered');
            a=accnew;
         system.debug(a);

        }    
    
        nameaccount=a.Name;
// Here getting the duplicate account into list based on account name
        lst_acc=[select id,name from Account where name=:nameaccount and id!=:a.Id];
        system.debug(lst_acc);
        for(Integer i=0;i<=lst_acc.size()-1;i++){
// Condition to send duplicate account into "i"
            if(lst_acc[i].Id !=a.Id){
                system.debug('continue');
                system.debug(lst_acc[i].name);
                system.debug(lst_acc[i].Id);

//Getting opportunity of duplicate account into lst_opp based on duplicate account Id
     lst_opp=[select id,accountid from opportunity where AccountId=:lst_acc[i].Id];  
                system.debug(lst_opp);       
        
        if(lst_opp!= null){   
         system.debug('Enetered Opp Loop');
            for(Integer j=0;j<lst_opp.size();j++){
              lst_opp[j].AccountId=a.Id;  
                system.debug('AccountId changed');
                   update lst_opp[j];
                system.debug( lst_opp[j].AccountId); 
            }
         }   
         } 
        }                                            
    }
}
}
 
NagendraNagendra (Salesforce Developers) 
Hi Bharghav,

Hi Bhargav,

You can update the Account of all child Opportunities of the first Account with no code by using Process Builder.

Hope this helps.

Please mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks,
Nagendra
Ravi@2018Ravi@2018
Hi Nagendra,

I have doubt how i am suppose set condtion(Add Criteria) in process builder to check newly insert account name with existing Account name.

Thanks,
Bhargav