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
Dhananjay Patil 12Dhananjay Patil 12 

How to Bypass Apex in "Account Merge"?

I have a requirement in which when click on delete button on the account it should allow you to delete only when its related contacts status  are inactive..Otherwise it should throw some error message on UI..
 I have solved this requirement by writing an apex code & Creating a new label where I can specify the message which is working fine but there is one standard scenrio where it failing ..When I merge 2 accounts if loosing accoun contains contact of active status then it is throwing me an error message but as per my requirement I have to bypass the code when it comes to the account...I have referred some docs about Trigger and Merge and found that MasterRecordID is getting set on lossing record.....but On winning record what kind of condtion should I specify so that it  works....because my coding is getting triggered on before delete event....
Srinivas SSrinivas S
Hi Dhananjay,
Please find the following solution -
Trigger AccountTrigger on Account(after delete) {
    for(Account acc : trigger.new) {
        //Only Merge deleted record will be having the MasterRecordId.
        if(String.isBlank(acc.MasterRecordId)) {
            //error you are displaying in trigger.
        }
    }
}

-------------------
Thanks,
Srinivas
- Please mark as solution if your problem is resolved.
Dhananjay Patil 12Dhananjay Patil 12
Hi Srinivasa,
Thanks for your reply...
The code that you have provided works only on after trigger... My main requiremennt works on before trigger....
I have written the following code on before trigger:

public void beforeDelete(SObject so) {
 Account accountToDelete = (Account)so;
if(accountToDelete .MasterRecordId==Null)
List<Contact> contacts = new List<Contact>([SELECT Id, Name,Inactive__c FROM Contact WHERE AccountId = :accountToDelete.Id AND Inactive__c=false]);
        
        if(contacts.size()>0 && String.isBlank(accountToDelete.MasterRecordId))
        {
            so.addError(Label.Active_Contact_Error);
        }
}



because in the query I only check those records whose status is Active and throws the validation error if the account contains any Active contacts...if account contains Inactive contacts then it allows me to delete...
but the above code fails only in the "Account Merge" Scenario because before delete call first as per the sequence of excution so  during the merge if loosing account contains Active contacts then it executs the if condition and throw me the validation message which I want to bypass......Please refer the code and let me know any suggession or condition that I can specify...