2

I've got a custom object with separate lookup fields for Lead and Contact. What I'd like is that when the record is saved with a lead or a contact, a trigger fires and pulls the Lead Source from the lead or contact (whichever was added) and saves it in a field for the custom object.

Can anyone point me in the direction of sample code to accomplish this?

1

I'll try to explain the process of creating this sort of Trigger. I'll explain it using bulkified techniques.

First - you want a before update, before insert trigger. This is because you can modify the fields of your custom object with no DML required if the trigger is before.

You now need to retrieve the values from Lead and Contact that are you want to update the custom object with.

Generally you loop over your list of custom objects and collect the ids you need to query on (I'll only do leads here):

Set<Id> leadIds = new Set<Id>();
for (CustObj obj : Trigger.new){
    leadIds.add(obj.LeadId__c);
}

Now, you need to query Leads using this set of Ids - the key thing is to make sure you build a Map object so you can retrieve the value you want later.

Map<Id,Lead> leads = new Map<Id,Lead>([SELECT Id, LastName From Lead Where Id IN :leadIds]);

Now you have a Map of Leads and a List/Map of your Trigger objects. The final part is to loop over your Trigger objects and extract the values from the Leads map. Since you have mapped by Id, you can do this like so:

for (CustObj obj : Trigger.new){
    Lead l = leads.get(obj.LeadId__c);
    if (l == null){
        continue; //skips this iteration of the loop
    }
    obj.Last_Name__c = lead.LastName; //or whatever field you are using.
}

No updates needed as you did this on a before trigger

Note, Querying Leads can be a pain if you are dealing with converted Leads. It might be a good idea to get this going with contacts first and then try leads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.