1

We're implementing a coupon program. The coupons are unique codes and are related to an existing customer and stored in a custom field on the Account.

When a Lead is created due to being referred using one of the unique coupons, the unique coupon is saved in a custom field on the Lead. I need to access the associated Account Id of the unique coupon.

I could do this by creating a trigger on lead insert and then query accounts looking for unique coupon. My concern with this approach is having a trigger and query on every lead created; seems this would not be good pratice - using so much resources for a rare situation

Is there another (better) approach; lookup?

Thanks

3
  • Only do it if the field is populated. And that's what triggers and automation are for. Designed properly it will be inconsequential
    – Eric
    Apr 12, 2017 at 2:23
  • @Eric Thanks for your response. Although, I"m a little confused on your statement "Only do it if the field is populated. And that's what triggers and automation are for" But triggers are "fired" off of objects not fields. All of our triggers (Lead, Opportunity, etc.) have Class handlers so if I used a trigger for this scenario, the trigger and class handler would be called on every Lead insert. Can you please elaborate? Thanks
    – user20719
    Apr 12, 2017 at 16:56
  • Your trigger/class would check if the field is populated and only do the query if it is
    – Eric
    Apr 12, 2017 at 16:57

1 Answer 1

0

As pointed out in the comments, a good practice for triggers is to check if relevant fields are being changed, along with bulkifying your code. You should have something like this:

// Access Leads before the update on your trigger
Map<Id, Lead> oldMap = trigger.oldMap;

// Find out which leads exactly changed, saving their coupon codes (used String here)
List<String> couponCodes = new List<String>();

for (Lead newLead : trigger.new) {
    Lead oldLead = oldMap.get(newLead .Id);
    if (oldLead.YourCouponField != newLead.YourCouponField) {
        couponCodes .add(newLead.YourCouponField);
    }
}

// Now query the Accounts for those changed Leads only
List<Account> accounts = [SELECT Id, Name FROM Account WHERE AccountCouponCode IN couponCodes];

I didn't understand what exactly you use to query the Accounts, but the general structure should be something like that. With this approach you will only make the query if that coupon field changed in the Lead, and will do that in a bulkified way for multiple Leads being updated.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .