+ Start a Discussion
Rajesh SFDCRajesh SFDC 

how delete records case object to custom object using apex trigger ?

here, my requirments whenever i am creating new records on case object, insert or update to custom object cases__C, suppose i want to delete records in case objects
that corresponding records delete in custom object cases__C.how to do ?

trigger CreateCases on Case (after insert,after update)
{

  Case cs=Trigger.new[0];
   Case csold=Trigger.old[0];
  if (Trigger.isInsert)
  {
     List<cases__C> caslist=new list<cases__C>();
     Cases__c ci=new Cases__c();
     ci.Case_Number1__c=cs.CaseNumber;
     ci.Origin__c=cs.Origin;
     ci.Priority__c=cs.Priority;
     ci.Status__c=cs.Status;
     ci.Type__c=cs.Type;
     ci.Description__c=cs.Description;
     ci.Subject__c=cs.Subject;
     ci.Reason__c=cs.Reason;
     insert ci;
     //calist.add(ci);
  }
  if(Trigger.isUpdate)
  {
  
    list <Cases__c> caupdate=new list<Cases__c>();  
    caupdate=[select id,Case_Number1__c,Origin__c,Priority__c,Status__c,Type__c,Description__c,Subject__c,Reason__c from Cases__c where Case_Number1__c =: cs.CaseNumber];
     integer si=caupdate.size();
     system.debug('-------------------'+si);
    
     for(Cases__c cx: caupdate)
     {
         cx.Case_Number1__c=cs.CaseNumber;
         cx.Origin__c=cs.Origin;
         cx.Priority__c=cs.Priority;
         cx.Status__c=cs.Status;
         cx.Type__c=cs.Type;
         cx.Description__c=cs.Description;
         cx.Subject__c=cs.Subject;
         cx.Reason__c=cs.Reason;
         update cx;
     }
   }
    Case csold=Trigger.old[0];
   if(Trigger.isDelete )
   {
  
    Cases__c casdel =new Cases__c();
     casdel =[select id,Case_Number1__c from Cases__c  where  Case_Number1__c =: csold.CaseNumber ];--------> delete records coding.
     if(casdel != NULL )
     {
      delete casdel;
      }
   }
  
}
Best Answer chosen by Rajesh SFDC
OnpursuitOnpursuit
Hi,

Please add the delete event:

trigger CreateCases on Case (after insert,after update, after delete)

If this resolves the issue then mark it as resolved.

Thanks

All Answers

OnpursuitOnpursuit
Hi,

Do you want to delete the custom related list records related to case?

Rajesh SFDCRajesh SFDC
no, i am creating new records in case object. i am created cusom object cases__c..  when insert or update or delete records in case object , insert and upate records to cases__c custom objects. inser or update working fine.. doesnot working delete option... 
OnpursuitOnpursuit
Hi,

Please add the delete event:

trigger CreateCases on Case (after insert,after update, after delete)

If this resolves the issue then mark it as resolved.

Thanks
This was selected as the best answer
Guru@SfCloudGuru@SfCloud
Hi Rajesh,

For event deletion better to use the Trigger.oldMap..........