+ Start a Discussion
Dheeraj-(DJ)Dheeraj-(DJ) 

Creating an Opportunity in SF and using trigger automatically a contact should be created and linked to Opportunity


Hello Team!

I am SF begineer and trying the below code, after creating Opportunity in SF, trigger automatically creates a contact but contact is not linking to Opportunity and not showing up as in related list.


trigger Op_Trigger3 on Opportunity (After Insert) {
Contact c = new Contact();
for(Opportunity o : Trigger.New)
{
c.AccountID = o.AccountID;
c.FirstName = 'Michael';
c.LastName = 'Scofield';
insert c;
}
}

I am not sure if something is missing in the trigger code or not. Please correct if I am making any mistake.

Thanks in Advance,
​Dheeraj
PawanKumarPawanKumar
Hi Dheeraj,

Step 1: Please use below modified code and follow step 2:

trigger Op_Trigger3 on Opportunity (After Insert) {

for(Opportunity o : Trigger.New)
{
Contact c = new Contact();
c.AccountID = o.AccountID;
c.FirstName = 'Michael';
c.LastName = 'Scofield';
insert c;
}
}

Step 2: There is no direct association of Contact with Opportunity unlike Account. So what you will have to do is: Just drill down as below and you will see your contact under account(Not under opportunity). 
Opportunity->Account->Contact

Regards,
Pawan Kumar
 
Onesh ReddyOnesh Reddy
Hi Dheeraj,

To relate Contact to an Opportunity you have to create OpportunityContactRole. Please try the below code.
Also I advise you to follow coding best practices and bulkify your code.
 
trigger Op_Trigger3 on Opportunity (After Insert) {
Contact c = new Contact();
for(Opportunity o : Trigger.New)
{
c.AccountID = o.AccountID;
c.FirstName = 'Michael12';
c.LastName = 'Scofield';
insert c;

// Create OpportunityContactRole to relate Contacts to Opportunities  
opportunitycontactrole ocr= new opportunitycontactrole();
ocr.contactid=c.id;
ocr.OpportunityId=o.id;
ocr.IsPrimary=true;
//ocr.Role='CEO';
insert ocr;
}   
}

Opportunity Contact Roles: https://help.salesforce.com/articleView?id=contactroles.htm&type=0
https://developer.salesforce.com/docs/atlas.en-us.sfFieldRef.meta/sfFieldRef/salesforce_field_reference_OpportunityContactRole.htm

Coding Best Practices : https://developer.salesforce.com/docs/atlas.en- (https://developer.salesforce.com/docs/atlas.en-us.sfFieldRef.meta/sfFieldRef/salesforce_field_reference_OpportunityContactRole.htm)

Let me know if it helps you.

Regards,
Onesh.K