+ Start a Discussion
ChemburChembur 

Update Account in Case

When an Account is deleted, I need to update all the related cases with a new 'matched' Account Id and then delete the Original Account.

In the BeforeDelete Trigger of Account, Cases attached to the account are being successfully updated to a new matched account

However, the Delete of Original Account fails, with message 'Delete failed. as account is still associated with Cases'

 

Any ideas on why the original Account is throwing an error and not being deleted ? Do I need to disassociate original account with the cases attached to it, at the account level. If so how ?

 

Thanks,

 

Vinit_KumarVinit_Kumar

Hi Chembur,

 

Try below code :-

 

trigger reassociateRelatedCases on Account (before delete) {

    List<Account> accList = new List<Account>();
    List<Id> accIds =  new List<Id>();
    List<Case> caseList = new List<Case>();
    List<Case> newcaseList = new List<Case>();
    
    for (Account ac : trigger.old){
        accIds.add(ac.id);
    
    }
    
    caseList=[select id,AccountId from Case where AccountId in:accIds];
    accList = [select id from Account where id in:accIds];
    
    
    for(Case cs : caseList){
    cs.AccountId = <some id>;
    newcaseList.add(cs);
    }
    update newcaseList;
   
}
ngabraningabrani

You do not need to delete the Original Account in the BeforeDelete Trigger of Account. The account is already being deleted in beforeDelete, so you do not need to explicitly delete the account again. If you can put your code here, it will be more clear what you are trying to do.

ChemburChembur

Vinit,

I have the exact same code as you have below  ina method in 'Account Trigger'

The code does the reassign of Account to Cases but fails on the Account Delete.

Account Trigger(before delete)

    if (Trigger.isDelete ){

               processReassociateRelatedCases (Trigger.old);

    }

 

Are you suggesting I call another Trigger instead of a method before Calling 'Account Delete Trigger' ?

I have more processing in the Account Trigger for Delete ? How do I make sure this new trigger and Account Trigger are called sequentially.

 

Thanks,

 

 

Vinit_KumarVinit_Kumar

Chembur,

 

Can you paste your Apex Class code here.

ChemburChembur

Nitin,


Thanks for your help. My issue was resolved, once I updated the ContactId along with AccountId on the Case. The generic Case error on the Account delete was due to deleting Contact. Once I updated both the AccountId and the ContactId on the cases, Account was successfully deleted.


Thanks,