I’m stuck on the syntax (and maybe the logic) of writing this Salesforce.com Trigger. I want the trigger to check to see if a primary contact is listed in the ContactRoles on the Opportunity. If there’s a primary listed, I need to lookup the LeadSource from the corresponding contact and insert that value in the the Lead Source of the Opportunity.
Any hints or tips are greatly appreciated!
trigger UpdateContactLeadSource on Opportunity (after insert, after update) {
//Declare the Lead Source Variable which will hold the contact's lead source
string leadsource;
// See if there is a primary contact listed on the Opportunity
for (Opportunity o : Trigger.new) {
OpportunityContactRole[] contactRoleArray =
[select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];
// If the there is a primary contact, then...
if (contactRoleArray.size() > 0) {
// Lookup ContactID on the Contacts table to find the lead source
for (Contact contact : [SELECT LeadSource FROM Contact WHERE Contact.Id = :OpportunityContactRole.ContactId LIMIT 1])
// Store the actual lead source in the leadsource variable
{ Contact.LeadSource = leadsource;}
update Opportunity.LeadSource = leadsource; }
}
}
There are couple of seriously bad things in your code. Hope you won’t feel offended, it’s a nice requirement and a learning opportunity too…
after insertdoesn’t make any sense here. By very definition if you’ve just finished inserting this Opportunity it won’t have any contact roles in it yet.*after updateis OK-ish.before updatewould be nicer because you’d just fill in the value and you’ll get the save to database for free.LeadSourceon Opportunity would be null?ORDER BY,LIMIT 1etc – Salesforce will protect you and allow only 1 contact to be primary. Even if you’d want to load them with such mistake with Data Loader.TL;DR
EDIT to answer question from comment re #3
You’d need similar but not identical code in a new trigger (in this case it doesn’t matter much whether it’s
beforeorafter– we need to explicitly update Opportunities). It’s a bit worse here also because the fields you want to look at aren’t directly available – you have access to OpportunityId, ContactId but not Contact.LeadSource. Something like this should do the trick:It gets interesting here because this update will fire our old trigger on opportunities. It should be fine if you have left my “skip if leadSource is filled in” but still you might want to explore 2 things:
Theoretically you could just “touch” the Opportunities without changing anything (treat the old trigger as a benefit, not unwanted side effect in this case). For me it’d look a bit too magical but if it’s well commented what’s going on here it might lead to less code, less logic duplication, less unit tests… It will work as long as it’s
aftertrigger so the query for contact roles we’ve just modified will see new values. It’d have to look like that