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
SasidSasid 

Trigger to delete a Cross Object Record

Could you please help me to write a trigger on Cross Object Record deletion.

Assume object A (Opportunity) and B (Contact Roles).
Object B is in related list of A.
Assume that there is a record in object B related to object A's record with name "ABCD".
Whenever a record is created on object B related to object A's record with name other than "ABCD", then the existing object B record named "ABCD" should be deleted.
v varaprasadv varaprasad
Hi Sasidharan,

Please check once below code : 
 
Trigger deleteRec on ObjectB__c(Before insert){

   Map<id,string> mpDetails = new map<id,string>();
   For(ObjectB__c ob : trigger.new){
       if(ob.objectA  != null){
         mpDetails.put(ob.objectA,ob.LastName);
       
       }   
   
   }

   List<ObjectB__c> existingLst = [select id,lastname from ObjectB__c where objectA in : mpDetails.keyset()
   and lastname Not In : mpDetails.values()];
  
   If(existingLst.size()>0) 
   Delete existingLst;
   
}

Hope this helps you.


Thanks
Varaprasad 


 
SasidSasid
Hi Prasad, I’m getting an error stating that variable (objectA) does not exists. if(ob.objectA != null){ Regards, Sasidharan
v varaprasadv varaprasad
objectA means parentid apiname and last name means u need to give name.

​in your case u need to give opportunityid instead of objectA

Thanks
Varaprasad
SasidSasid
Hi Prasad, Trigger deleteRec on ObjectB__c(After insert, After update){ Map mpDetails = new map(); For(ObjectB__c ob : trigger.new){ if(ob.Session__c != null){ mpDetails.put(ob.Session__c,ob.SessionName__c); } } List existingLst = [select id,SessionName__c from ObjectB__c where Session__c in : mpDetails.keyset() and SessionName__c Not In : mpDetails.values()]; If(existingLst.size()>0) Delete existingLst; } Regards, Sasidharan