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
Anas AlamourAnas Alamour 

trigger update field in parent record when delete a child record

Hi All , i am a new to Apex triggers. i have requirment to update checkbox field in a parent record when delete a child record , this update also based on a specfic condiiton. can anyone help me how to write this trigger and test class code , so i can deploy it to the production. Thanks. 
AbhinavAbhinav (Salesforce Developers) 
Hi Anas,

You can take reference from below link for updating parent record on deletion of child.

You just need to modify it as per your scenario.

https://salesforce.stackexchange.com/questions/155061/updating-parent-field-after-child-record-is-deleted

If it helps please mark it as best answer.

Thanks!
CharuDuttCharuDutt
Hii Anas
Try Below Code
trigger TestTrigger on Contact (after delete) {
	set<Id> lstId = new set<Id>();
    for(Contact Con :trigger.old){
        lstId.add(Con.AccountId);
    }
    
    list<Account> lstAcc = [select id,Check2__c From Account Where Id IN :lstId];
    for(Account Acc :lstAcc){
        Acc.check2__c = true;
    }
    update lstAcc;
}

Test Class
@isTest  
public class TestTriggerTest {
    @isTest    
    public static void UnitTest() {
        Account Acc = new Account();
        Acc.Name = 'test ACC';
        Insert Acc;

        Contact Con = new Contact();
        Con.FirstName='Test';
        Con.LastName='Con';
        Con.AccountId = Acc.id;
        Insert Con;
        Delete Con;
   }
}
Please Mark It As Best Answe If It Helps
Thank You!

 
Suraj Tripathi 47Suraj Tripathi 47
Hi Anas,

use this code of trigger:
trigger TestTrigger on Contact (before delete) {
    set<Id> parentID_Set = new set<Id>();
    for(Contact con :trigger.new){
        parentID_Set.add(con.AccountId);
    }
    system.debug(parentID_Set);
    list<Account> accList = [select id,Check2__c From Account Where Id IN : parentID_Set];
    for(Account acc :accList){
        acc.check2__c = true;
    }
    update accList;
}
---------------
If you find your Solution then mark this as the best answer to close this question. 

Thank you!
Regards,
Suraj Tripathi