function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
FrankFFrankF 

Lead_AfterInsert trigger and Campaigns

A little backgroud:

 

We have a field - Qualifying_Campaign__c that is required to be filled when a lead's status changes from Prospect to Qualified Lead. The reason for the field is that a Lead may be a member of multiple Campaigns but the Qualifying Campaign is the campaign that actually qualified the change of status.

 

Now, we have a partner that pushes leads to us using a Web To Lead form. They are correcly setting the CampaignId on the Web to Lead form. The requirement is then that since these leads are prequalified, I need to set the Status to Qualified Lead when the Lead comes into SFDC and I need to set the Qualifying_campaign__c to the CampaignId that was pushed.

 

So I wrote a trigger that accomplishes this.

 

trigger Lead_AfterInsert on Lead (after insert) {

List<Id> leadids = new List<Id>();

for (Lead thisLead : Trigger.New)

leadids.add(thisLead.Id);

Lead[] leads = [select Id, LeadSource, Status, Qualifying_Campaign__c, custom_lead_src__c, (Select CampaignId from CampaignMembers order by CreatedDate limit 1) from Lead where Id in :leadids];

 

for (Lead l : leads) {

//Do the eTrigue thang

 if (l.LeadSource == 'eTrigue' && l.Custom_Lead_Src__c != '') {

try {System.debug(

'CampaignMembers isEmpty = ' + l.CampaignMembers.IsEmpty()); if (!l.CampaignMembers.IsEmpty()) {

l.LeadSource = l.Custom_Lead_Src__c;

l.Status = 'Qualified Lead';

l.Qualifying_Campaign__c = l.CampaignMembers[0].CampaignId;

update l;

}

} catch (DMLException e) {System.debug(

'DMLException Occurred:' + e.getMessage());

}

}

}

}

 

So all is well until it comes time to write the TestClass for this trigger. How the heck do I simulate the insertion of the Lead with a CampaignId?

 

If I create the Lead, and then insert the CampaignMember record, the Lead_AfterInsert trigger will already have fired!

 

Any ideas would be much appreciated.

 

Frank.

paul-lmipaul-lmi
have you looked into using a Visualforce page and Sites to achieve this rather than a trigger?  It'd be cleaner, and negate impact to other lead-generating mechanisms that you may have in place now or in the future while giving you full flexibility to do all this as part of the insertion rather than doing an immediate update afterwards.
FrankFFrankF

I'm not sure why a VisualForce page would be cleaner than the trigger. Perhaps you could expand on that?

 

Also intellectually, I'd still like to know how I'd test the trigger that I wrote.

 

Thanks.