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

Trigger Help Update Contact and Lead


I've build a trigger that updates a status of a campaign member when he answers a web-to-case form,when the user is a lead or a contact,so far so good, my problem is when a lead has  a same e-mail as a contact my trigger ignores the contact e-mail and only updates the status of the lead. When this scenario happen i want to both to be updated if both have the same e-mail.

This is my code :
trigger bi_WebToCaseLead on Case (before insert) {

List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true];
Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>();

    for(CampaignMember cm : listCm){
        mapCm.put(cm.Lead.Email, cm);
        mapCm.put(cm.Contact.Email, cm);  
    for(Case caso :{
        Case tempCase = caso;
        CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail);

        if(tempCampaign != null && caso.ChaveCampanha__c !=null){
          tempCampaign.Status = 'Respondido';
          caso.RelacionamentoLead__c = tempCampaign.LeadId;
          update tempCampaign;        

First of all, a couple of general remarks regarding this trigger:

- update tempCampaign is inside a loop. Better to put them in a list and do 1 update at the end.
- The first SELECT statements is not filtering on the context of the current trigger. 

Otherwise you will not have a trigger that will scale

To solve your problem, if i understand, why not create 2 MAPs: one for leads, one for contacts. And check on those 2 ?