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
Rohan SRohan S 

Trigger not getting executed properly

I'm wrtting a trigger which restricts an account to be deleted if it has opportunities. Below is the Apex class & trigger.

Apex Class:
public class RestrictAccountDeleteClass
{
public static void RestrictAccountDelete(list<account>AccList)
{
list<account> OldAccList = new list<account>();
OldAccList = [SELECT Id, (SELECT Id FROM Opportunities ) FROM Account WHERE Id IN : AccList];
for(Account a : OldAccList)
{
if(a.Opportunities.size()!=0)
{
a.addError('Cannot delete account as it has associated opportunities');
}
}
}
}

Trigger:
trigger RestrictAccountDeleteTrigger on Account (before delete) {
if(trigger.isBefore==true && trigger.isDelete==true){
RestrictAccountDeleteClass.RestrictAccountDelete(trigger.old);
}
}

When I try to delete a record, it gives the following error: Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger RestrictAccountDeleteTrigger caused an unexpected exception, contact your administrator: RestrictAccountDeleteTrigger: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Class.RestrictAccountDeleteClass.RestrictAccountDelete: line 11, column 1".

Can someone please let me know where I am going wrong?
Best Answer chosen by Rohan S
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rohit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Handler:
public class Handler_DeleteAccError {
    
    public static void RestrictAccountDelete(List<Account> accList){
        Set<Id> accountIds = new Map<Id, AggregateResult>(
            [SELECT AccountId Id 
             FROM Opportunity 
             WHERE AccountId=:accList
             GROUP BY AccountId]).keySet();
        for(Account record : accList) {
            if(accountIds.contains(record.Id)) {
                record.addError('Please delete all opportunities before deleting the account.');
            }
        }
        
    }
}

Trigger:
trigger DeleteAccError on Account (before delete) {
    
    if(trigger.isBefore && trigger.isDelete){
        Handler_DeleteAccError.RestrictAccountDelete(trigger.old);
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Team NubesEliteTeam NubesElite
Hi Rohit,
Please try this code it may help you
trigger AccountOppCheck on Account (before delete) { 
        List<opportunity> Opportunity = [select accountid from opportunity where accountid in : Trigger.oldMap.keySet()];
        set<id> accIds = new set<id>();
          for(opportunity opp : opportunity)
                 accIds.add(opp.accountid);
        for(account acc:trigger.old)
            if(accIds.contains(acc.id))
                acc.adderror('******* opportnuty is associated with it.you cant delete account');            
    }



Thank You
www.nubeselite.com

Developement | Training | Consulting

Please mark this as solution if your problem resolved.
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rohit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Handler:
public class Handler_DeleteAccError {
    
    public static void RestrictAccountDelete(List<Account> accList){
        Set<Id> accountIds = new Map<Id, AggregateResult>(
            [SELECT AccountId Id 
             FROM Opportunity 
             WHERE AccountId=:accList
             GROUP BY AccountId]).keySet();
        for(Account record : accList) {
            if(accountIds.contains(record.Id)) {
                record.addError('Please delete all opportunities before deleting the account.');
            }
        }
        
    }
}

Trigger:
trigger DeleteAccError on Account (before delete) {
    
    if(trigger.isBefore && trigger.isDelete){
        Handler_DeleteAccError.RestrictAccountDelete(trigger.old);
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
Rohan SRohan S
Thanks Anas. It worked.
Deepali KulshresthaDeepali Kulshrestha
Hi Rohit

Try this code.
trigger ResAccount on Account (before delete) {
    if(Trigger.isBefore && Trigger.isDelete){
        RestrictAccountDeleteClass.resAccDelete(Trigger.old);
    }

}



public class RestrictAccountDeleteClass {
    public static void resAccDelete(List<Account> acc){
        List<Opportunity> lopportunity=[select Id,Name,AccountId from Opportunity where AccountId in:acc];
        System.debug(lopportunity);
        for(Account ac:acc){
        for(Opportunity op:lopportunity){
            if(op.AccountId==ac.id){
                 ac.addError('You can not delete Account ');
            }
        }
        }
        
    }

}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com