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
LBartonLBarton 

Apex Trigger in Opportunity to Update Contact Custom fields

I am creating a trigger on Opportunity which will do the following according to the stage it is in. It will update the contact custom fields for all those who have a contact-role for the opportunity. thanks for any advice and help!

II the opportunity stage is prospecting or qualification, then do nothing.

If the Opportunity stage is Needs Analysis, Values Proposition, Perception Analysis , or Negotiation Review, 
but the status is not Open4.
then add the name of the opportunity to the custom field MQL__c in Contact (If the name is not already listed there in a semicolon delimited list.)

If the Opportunity is Closed-won, then add the name of the opportunity to the custom field Customer__c in Contact. (If the name is not already listed there in a semicolon delimited list.)

What I have so far will only add the opportunity name to the  MQL__c field, but I would have to remove the name, for instance, if the stage changes to closed-won from Negotiation review.
I also have not taken care of closed-won opportunities.

I am not sure that the opportunity name will be correct. All I am using is oOppName = o.Opportunity__c; I probably need to do something different from that.
//This trigger will update the custom lifecycle stages fields on the contacts who have a contact-role for this opportunity
	if (!trigger.isDelete) {
	        	    
       		set<Id> ContactIDs = new set<Id>();
       		set<Id> oppIds = new set<Id>();
       		List<Contact> ContactToUpdate = new List<Contact>() ;     
       		string oOppName = '';
       		                
            for(opportunity o:trigger.new){
                oppIds.add(o.Id);
                
                oOppName = o.Opportunity__c;
                
                try {
       				OpportunityContactRole contactRole = [select ContactId, OpportunityID from OpportunityContactRole where OpportunityId IN :oppIds];
       				if (contactRole != null) {
       					ContactIDs.add(contactRole.ContactId);
       				}
                }
                catch (Exception e){
                	OpportunityContactRole contactRole = new OpportunityContactRole();
                }
       			
            }
            for(Contact oc:[select MQL__c,
                             (
                             select stagename,opportunity__c from opportunities 
                             where stageName IN ('needs analysis', 'negotiation/review','perception analysis','value proposition')                             
                             and Id IN :oppIds
                             ) 
                           from Contact 
                           where Id IN :ContactIDs])
            {
                string oOppList = '';
                Contact oContact = new Contact();
                oContact = oc;
             	
             	if (oContact.MQL__c != null) {
             		oOppList = oContact.MQL__c;
             	}
                if(oOpplist.contains(oOppname)==false){ 
					oOpplist = oOpplist + ';' +  oOppname;
                }
				
        		oContact.MQL__c = oOpplist;
        		ContactToUpdate.add(oContact);
        		
        		if (ContactToUpdate.size() > 0){
        			update ContactToUpdate;
        		}
        			
            }            
       		
	}

 
PratikPratik (Salesforce Developers) 
Hi,


for(opportunity o:trigger.new){
oppIds.add(o.Id);
oOppName = o.Opportunity__c;


Here if you want to have opportunity name, you can use
oOppName = o.name;

I am not sure what this custom field Opportunity__c you are using.

Thanks,
Pratik
LBartonLBarton
The o. opportunity__c field is the same as the o.name one. I save the opportunity IDs in a set. 
oppIds.add(o.Id);
Would I need to sae the opportunity name in a set as well for any reason? I want to make sure I always have the correct opportunity name.


 
LBartonLBarton
I think I am not getting filtering from the stages. I think I get all the opportunity-contact-role people from an opportunity, regardless of the stage.  I do not think the following is working to limit the opportunities according to stages.

  select stagename,opportunity__c from opportunities
                            where stageName IN ('needs analysis','negotiation/review','perception analysis','value proposition')                            
                             and Id IN :oppIds
 
LBartonLBarton
I changed the trigger again.  Is there any way to make this more efficient? Thanks!

 //This trigger will update the custom lifecycle stages fields on the contacts who have a contact-role for this opportunity
 if (!trigger.isDelete) {
             
         set<Id> ContactIDs = new set<Id>();
         set<Id> oppIds = new set<Id>();
         set<Id> OppIdsFiltered = new set<id>();
         list<Contact> ContactToUpdate = new list<Contact>() ;    
         string oOppName = '';
                      
            for(opportunity o:trigger.new){
                oppIds.add(o.Id);
                oOppName = o.Opportunity__c;
            }
           
            try {
       Opportunity oFilteredOpp = [select ID from Opportunity where Id IN :oppIds
        and stageName IN ('needs analysis', 'negotiation/review','perception analysis','value proposition') 
                         and status__c != 'Open 4'];
       if (oFilteredOpp != null) {
        OppIdsFiltered.add(oFilteredOpp.iD);
       }
            }
            catch (Exception e){
             Opportunity oFilteredOpp = new Opportunity();
            }
                         
           
            try {
       OpportunityContactRole contactRole = [select ContactId, OpportunityID from OpportunityContactRole where OpportunityId IN :OppIdsFiltered];
       if (contactRole != null) {
        ContactIDs.add(contactRole.ContactId);
       }
            }
            catch (Exception e){
             OpportunityContactRole contactRole = new OpportunityContactRole();
            }    
                      
            for(Contact oc:[select SQL__c from Contact where Id IN :ContactIDs])
            {
                string oOppList = '';
                Contact oContact = new Contact();
                oContact = oc;
              
              if (oContact.SQL__c != null) {
               oOppList = oContact.SQL__c;
              }
                if(oOpplist.contains(oOppname)==false){
     oOpplist = oOpplist + ';' +  oOppname;
                }
    
          oContact.SQL__c = oOpplist;
          ContactToUpdate.add(oContact);
        
            }
          
         if (ContactToUpdate.size() > 0){
          update ContactToUpdate;
         }              
                 
            OppIdsFiltered.clear();
            ContactIDs.clear();
             
            try {
       Opportunity oFilteredOpp = [select ID from Opportunity where Id IN :oppIds
        and stageName IN ('closed won') and status__c != 'Open 4'];
       if (oFilteredOpp != null) {
        OppIdsFiltered.add(oFilteredOpp.Id);
       }
            }
            catch (Exception e){
             Opportunity oFilteredOpp = new Opportunity();
            }
               
            try {
       OpportunityContactRole contactRole = [select ContactId, OpportunityID from OpportunityContactRole where OpportunityId IN :OppIdsFiltered];
       if (contactRole != null) {
        ContactIDs.add(contactRole.ContactId);
       }
            }
            catch (Exception e){
             OpportunityContactRole contactRole = new OpportunityContactRole();
            }
                     
            for(Contact oc2:[select Customer__c, SQL__c from Contact where Id IN :ContactIDs])
            {
                   
    string oOppList = '';
    Contact oContact2 = new Contact();
                oContact2 = oc2;
               
              if (oContact2.SQL__c != null) {
               oOppList = oContact2.SQL__c;
               oOppList = oOpplist.replace(';' + oOppName, '');
     oContact2.SQL__c = oOppList;           
              }
              
    oOppList = '';
              if (oContact2.Customer__c != null) {
               oOppList = oContact2.Customer__c;
              }
                if(oOpplist.contains(oOppname)==false){
     oOpplist = oOpplist + ';' +  oOppname;
                }
    
          oContact2.Customer__c = oOpplist;
    ContactToUpdate.add(oContact2);              
            }
           
            if (ContactToUpdate.size() > 0){
          update ContactToUpdate;
         }    
                 
 }
PratikPratik (Salesforce Developers) 
Hi,

You don't need to save opportunity name as long as you have opportunity ids.
One thing you can do is, put System.debug statement to check the values that returning so you can easily debug the code.

Thanks,
Pratik
LBartonLBarton
Thanks for your help, Pratik!  I hope you have a great new year!