You need to sign in to do that
Don't have an account?
Cross-Object Trigger (before insert, before update)
Hello,
Please help me on this trigger !!!
The trigger is on Lead and needs to fire only when
1. A checkbox field (Convert__c ) in Lead in selected.
2. The custom object (Obj2__c) has only 3 similar fields of Leads i.e Compnany__c, Date__c and Location__c which needs to be inserted or updated.
I wrote the below trigger, it is working good but it creates duplicates whenver a record is updated. Can anyone please help me in showing how to avoid duplicates. I am also not sure if I have to use before insert or after insert.
CODE:
trigger abc on Lead (after insert, after update) // Not sure if I can use before or after
{
List<Obj2__c> list = new List <Obj2__c> {};
for (Lead lead : trigger.new)
{
if (lead.Convert_c == true)
{
list .add(new Obj2__c
(Company__c = lead.Company,
Date__c = lead.Date__c,
Location__c = lead.Location__c) );
}
}
insert list;
}
Thanks for your help.
Adds a second criteria to compare the old value of the record with the new value and only performs the update if they are different. Had to split the update because trigger.old is only available in update/delete triggers.
I am not sure but you may have to put a check on the insert statement to see if the list contains any items. Something like if(list.size()>0) insert list; You can try it as written and then change it if it throws a dereference null object exception.
Let me know if you have any questions.
Hi Jake,
Thanks for your solution, I did implement your inputs in my code. Apart from that I also compared LeadId which helped me prevent duplicates.
Thanks,
Marc