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
Kai CheungKai Cheung 

Trigger CreateContactRole on Opportunity

Hi Newbie here,

In my Opportunities Tab, I have a lookup field called "relationship manager".  It looks up Contact for the relationship manager.

My goal is to write a trigger that when create or update an Opportunity and input the Relationship manager fields, it automatically create a Contact Role for the same person.

This is what i have so far, I dont know how to extract Opp ID and Contact ID as I think I will need it.  Please help.

Trigger CreateContactRole on Opportunity (after insert, after update)
{
For (Opportunity N:Trigger.now)

Opportunitycontactrole A = New Opportunitycontactrole ();
A.oppid = n.oppid;
a.RMID = n.rmid;
a.Role = ‘Relationship Manager’;
a.Isprimary = ‘True’;
}
Kai CheungKai Cheung
Maybe a more refine attempt here,

Trigger CreateContactRole on Opportunity (after insert, after update)

{For (Opportunity N:Trigger.now)

Opportunitycontactrole A = New Opportunitycontactrole ();
A.OpportunityId = N.id;
A.ContactId = THE CONTACT OJBECT ID NUMBER SUCH THAT IT MAtches the field's NAme in Opportunity;
A.Role = ‘Relationship Manager’;
A.IsPrimary = ‘True’;
   
}
Sagarika RoutSagarika Rout
Hi

      Your logic is correct but some condition we need to add on trigger logic , so that it will not execute if the entry criteria will not match.
   And another thing is always we need to make trigger as bulkify to overcome salesforce governer limits.

Trigger CreateContactRole on Opportunity (after insert, after update)
      {
         //Declaring list to insert listof Opportunitycontactrole
		 list<Opportunitycontactrole> listOfOpportunitycontactrole = new list<Opportunitycontactrole>();
		 For (Opportunity N:Trigger.new)
         {
		    if(N.relationship_manager__c != null){ //give proper API name , if this is not the one.
			   Opportunitycontactrole A = New Opportunitycontactrole ();
			   A.OpportunityId = N.Id;
			   A.ContactId = N.relationship_manager__c
			   A.IsPrimary = 'True';
			   listOfOpportunitycontactrole.add(A);
			}
			
		}
		//checking whether list is empty or not
		if(!listOfOpportunitycontactrole.isEmpty()){
		     insert listOfOpportunitycontactrole;
		}
           
    }

Kai CheungKai Cheung
Sagarika,

I follow you and Im so happy you responded,  the A.contactid requires  a string of numbers right? instead of the N.relationship_Manager__C which is a name?   Isnt what I want the ContactID number that matches the name on my opportunity field "relationship manager"???


Sagarika RoutSagarika Rout
No , It is nither a string nor a number , its a ID field.

You might get confused if it is a ID , how it displays name of the contact in UI instead of ID.
Let me  clarify you confusion , whenever you will create a look up / master detail relationship with and object, while creating record on child , internally salesforce will store the parent ID of  parent record on relationship filed but in UI the name of the parent record will visible.
 So far your requirement ,

You might create contact as a look up on opportunity (filed : relationship manager)

so when ever you will create opportunity , by selecting contact , it will view the contact name instead of ID while creating record on opportunity, but if you quiery this filed based on record Id , it will return the contactID instead of Contact Name.

So please execute the above trigger , autometicly you will undestand what i mean to say !!!!

if you have any confusion , please let me know.

Kai CheungKai Cheung
PERFECT!!!!!!!!!!!!!!!!


THanks!!!!!!!!!!!!!!  With more practice ill get better.


Thanks so much
Kai CheungKai Cheung
@Sagarika Rout

It works fine however, everytime I update, it creates another one of the contactrole.  How do I fix that?
Sagarika RoutSagarika Rout
Hi ,
 
      Sorry for the logic mistake . As i have not restrict the trigger , it was firing in both the  cases(insert and update) and creating duplicate records.
I have modified my logic , Please find below.
Trigger CreateContactRole on Opportunity (after insert, after update)
      {
         //Declaring list to insert listof Opportunitycontactrole
         list<Opportunitycontactrole> listOfOpportunitycontactrole = new list<Opportunitycontactrole>();
         For (Opportunity N:Trigger.new)
         {
            if(N.relationship_Manager__C != null){ //give proper API name , if this is not the one.
               Opportunity Old_Opportunity = Trigger.oldmap.get(N.Id); // to check whether you are updating relation manager field or not.
               if(Old_Opportunity.relationship_Manager__C!=N.relationship_Manager__C){
                   Opportunitycontactrole A = New Opportunitycontactrole ();
                   A.OpportunityId = N.Id;
                   A.ContactId = N.relationship_Manager__C;
                   A.IsPrimary = True;
                   listOfOpportunitycontactrole.add(A);
               }
               
            }
            
        }
        //checking whether list is empty or not
        if(!listOfOpportunitycontactrole.isEmpty()){
             upsert listOfOpportunitycontactrole;
        }
           
    }

Kai CheungKai Cheung
Thanks so much, same logic i had thought in mind.

I think my problem is i don tknow how to write whats in my mind.

For example  Old_  , trigger.oldmap.get()  is something i did not know or what it is commanding?

Also Object K = new object()   other than 'new' is there something else i can command?

is there a place I can read to get all these commands???

thanks so much again.
Kai CheungKai Cheung
Sagarika Rout,

I think it wont work because there is no old ID when and if we create a new opportunity. I think it will break.  
Kai CheungKai Cheung
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateContactRole caused an unexpected exception, contact your administrator: CreateContactRole: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.CreateContactRole: line 8, column 1
Kai CheungKai Cheung
Hello,

I worked around it by creating 2 trigger. One is after insert  the second after update.

First one is the orginial code
Second one is the revised code

the combination works.

What do you think?
Sagarika RoutSagarika Rout
yes, same way i tried in my developer org, as in after insert, you will not get any data in oldmap.
For this reason we are not getting any error while updating and as it returning null values in insert, so it is throwing exception while inserting records to database .
To overcome this exception , we need to use trigger context variables like "isinsert" and "isupdate" , which will differentiate between insert and update.
Salesforce has recommended one trigger per object, if there is complex logic which will not be fulfilled by single trigger , then only we should go for two triggers.
This scenario can be achieved by single trigger as well.
Trigger CreateContactRole on Opportunity (after insert, after update)
      {
         map<id,Opportunitycontactrole> map_OppID_Opportunitycontactrole = new map<id,Opportunitycontactrole>();
         //Declaring list to insert listof Opportunitycontactrole
         list<Opportunitycontactrole> listOfOpportunitycontactrole = new list<Opportunitycontactrole>();
         for(Opportunitycontactrole contactRole : [select OpportunityId,ContactId,IsPrimary from Opportunitycontactrole where OpportunityId In : Trigger.newmap.keyset()]){
            map_OppID_Opportunitycontactrole.put(contactRole.OpportunityId,contactRole);
         }
         For (Opportunity N:Trigger.new)
         {
            if(N.relationship_Manager__C != null && trigger.isinsert){ //give proper API name , if this is not the one.
                   Opportunitycontactrole A = New Opportunitycontactrole ();
                   A.OpportunityId = N.Id;
                   A.ContactId = N.relationship_Manager__C;
                   A.IsPrimary = True;
                   listOfOpportunitycontactrole.add(A);
               
            }
            if(N.relationship_Manager__C != null && trigger.isupdate){
              Opportunity Old_Opportunity = Trigger.oldmap.get(N.Id);
               if(Old_Opportunity.relationship_Manager__C!=N.relationship_Manager__C){
               //check if there is some existing contact role present in this opportunity
                  if(map_OppID_Opportunitycontactrole.get(N.Id)!=null){
                       Opportunitycontactrole A = map_OppID_Opportunitycontactrole.get(N.Id);
                       A.ContactId = N.relationship_Manager__C;
                       A.IsPrimary = True;
                       listOfOpportunitycontactrole.add(A);
                   }else {
                       Opportunitycontactrole A = New Opportunitycontactrole ();
                       A.OpportunityId = N.Id;
                       A.ContactId = N.relationship_Manager__C;
                       A.IsPrimary = True;
                       //system.debug('Opportunitycontactrole--->'+Opportunitycontactrole);
                       listOfOpportunitycontactrole.add(A);
                   }
               }
            }
            
        }
        //checking whether list is empty or not
        if(!listOfOpportunitycontactrole.isEmpty()){
             upsert listOfOpportunitycontactrole;
        } 
    }