You need to sign in to do that
Don't have an account?
shweta chadha 4
I have two objects contact and contact Relationship. Contact has a lookup on contact relationship. Contact relationship is a related list on contact object. deleting contact record should delete associated contact relationship record too.
here is my code:
trigger DeleteContact on Contact (after delete) {
if(trigger.isbefore)
{
if (trigger.isdelete)
{
set<id> idset = new set<id>();
for (Contact c : Trigger.old)
{
idset.add(c.Id);
}
List <Contact_Relationship__c> CR = [Select id from Contact_Relationship__c where id IN:idset];
delete CR; }
}}
trigger DeleteContact on Contact (after delete) {
if(trigger.isbefore)
{
if (trigger.isdelete)
{
set<id> idset = new set<id>();
for (Contact c : Trigger.old)
{
idset.add(c.Id);
}
List <Contact_Relationship__c> CR = [Select id from Contact_Relationship__c where id IN:idset];
delete CR; }
}}
trigger TriggerChildRecords on Contact (before delete) {
//To store parent ids
list<id> AccountIds=new list<id>();
for(Contact accountVar:trigger.old)
{
AccountIds.add(accountVar.id);
}
//Collecting all child records related to Parent records and Please use the Custom lookfield name in SOQL below don't use ID here am using my field API name is Contact__c
list<Contact_Relationship__c> listOfContacts=[select id from Contact_Relationship__c where Contact__c in :AccountIds];
system.debug('listOfContacts'+listOfContacts);
//deleting child records
delete listOfContacts;
}
Let me know if it works or not!!!
If it works mark this as a best answer!!!
Thanks,
Raj
All Answers
This is optimized code.
Please try the below code:
trigger TriggerTo_Delete_ChildRecords on Contact (before delete) {
//To store parent ids
list<id> ContactIds=new list<id>();
for(Contact con:trigger.old)
{
ContactIds.add(con.id);
}
//Collecting all child records related to Parent records
list<Contact_Relationship__c> listOfContactschild=[select id from Contact_Relationship__c where ContactId in :ContactIds];
system.debug('listOfContactschild'+listOfContactschild);
//deleting child records
delete listOfContactschild;
}
Let me know if it works or not!!!
If it works mark this as a best answer!!!
Thanks,
Raj
trigger TriggerChildRecords on Contact (before delete) {
//To store parent ids
list<id> AccountIds=new list<id>();
for(Contact accountVar:trigger.old)
{
AccountIds.add(accountVar.id);
}
//Collecting all child records related to Parent records and Please use the Custom lookfield name in SOQL below don't use ID here am using my field API name is Contact__c
list<Contact_Relationship__c> listOfContacts=[select id from Contact_Relationship__c where Contact__c in :AccountIds];
system.debug('listOfContacts'+listOfContacts);
//deleting child records
delete listOfContacts;
}
Let me know if it works or not!!!
If it works mark this as a best answer!!!
Thanks,
Raj