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
mansimansi 

delete a record using trigger

Hello, 

I have to implement a delete functionality in my trigger. 

trigger is on the child object of the account.

in this trigger when any record on the child object is created then it gets updated on the main Parent account  object. now is there any way by which when the same record gets deleted from the child object  it should be deleted from the parent account also

Please find my trigger below

trigger ABC on ChildObject (after insert,after delete) {
    
Set<Id> accId = new Set<Id>();
//Map<Id,Account> IdValues = new Map<Id,Account>();

if(trigger.isinsert)
{

for(ChildObject  CO : trigger.new)
    {
      accId.add(CO.ChildObject ID);
    }
    
    Map<Id,Account> IdValues = new Map<Id,Account>([select id, Industry__c from Account where id in:accId]);
    if(trigger.isinsert){
    for(ChildObject  CO : trigger.new)
    {
   
      string strInt=IdValues.get(CO.ChildObject ID).Industry__c;
      IdValues.get(CO.ChildObject ID).Industry__c=(strInt==null?'':strInt) +';'+ CO.Industry__c;
      
    }
    
    update IdValues.values();
}
}/*

if(trigger.isdelete){
 
 for(ChildObject  CO : trigger.old)
   {
   
   <delete functionality >
      
   
   }
   }
}

DiscussionDiscussion

Hi Mansi,

 

After looking at your code I am not able to understand that if you are writing trigger on child of account then how could 'child' field of child object (on which trigger is written) can refer the account again.

 

Any ways may be the Account reference field you have named as Child.

 

In that case for the delete operation you have to perform Exactly the same steps but using the Trigger.old list instead of Trigger.new List which is not accesible in Delete triggers. Below statements also need to be updated.

 

 string strInt=IdValues.get(CO.ChildObject ID).Industry__c;

if( strInt != null && strInt != '' && strInt.contains( CO.Industry__c)){

            String [] strlst = strInt.substring(CO.Industry__c);

            String temp = ' ' ;

            if(strlst!=null && strlst.size() > 0){

for(String str : strlst)

                  temp  += str

            }

       IdValues.get(CO.ChildObject ID).Industry__c=temp;    

}
      

Please test I think it will work ...