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
ApolloSApolloS 

Help with trigger. Copy Primary Campaign Source from 1st Opp. to newer w/ same Account?

We have a business rule, that if 1st Opportunity created under the Account has a Primary Campaign Source set to a certain Campaign, then every opportunity after has to have save Primary Campaign Source.

Issue is, sales people forget to enter that, or don't bother looking it up, if they are in a rush.

So I need a trigger, that looks up 1st Opportunity under the Account (which is set to Type = New Business) and copies the Primary Campaign Source from that Opportunity, to any subsequent Opportunities under the same Account.

How do I go about doing that?

Best Answer chosen by Admin (Salesforce Developers) 
mikefmikef

Sounds like a very good use case for Apex to solve.

 

Here is how I would solve it.

 

trigger OpportunityTrigger on Opportunity (before insert){
   if(trigger.isBefore()){
      if(trigger.isInsert()){
         OpportunityUtil.stampPrimaryCampaign(trigger.new);
      }
   }

}

 

public class OpportunityUtil{

   public static void stampPrimaryCampaign(Opportunity[] pOpptys){
      Set<Id> accIds = new Set<Id>();
      Map<Id, Opportunity> opptyMap = new Map<Id, Opportunity>();
      
      for(Opportunity opp : pOpptys){
         if(opp.AccountId != null){
            accIds.add(opp.AccountId);
         }
      }
      if(accIds.size() > 0){
         for(Opportunity opp : [select Id, AccountId, Primary_Campaign__c from Opportunity where AccountId in : accIds order by CreatedDate asc]){
            opptyMap.put(opp.AccountId, opp); //adding all the values to the map over rides all the same opptys under the same account so we order by created date and get the first oppty last.
         }

         for(Opportunity opp : pOpptys){
            if(opptyMap.containsKey(opp.AccountId){
               opp.Primary_Campaign__c = opptyMap.get(opp.AccountId).Primary_Campaign__c;
            }
         }
      }
   }

}

 

 

Please keep in mind I did not test this code or write it in a IDE. You will need to make it production ready by adding checks and testing it in sandbox.

 

It's meant as a starting point and not an implementation of your use case.