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
Mita PandyaMita Pandya 

When new opportunity is created, I would like to auto populate contact role.

SwethaSwetha (Salesforce Developers) 
HI Mita,
A similar ask was posted earlier on https://salesforce.stackexchange.com/questions/296280/automatically-create-contact-role-on-opportunity-creation# that should help you get started.

If this information helps, please mark the answer as best. Thank you
Suraj Tripathi 47Suraj Tripathi 47

Hi Mita,

Please find the solution. "When new opportunity is created, I would like to auto populate contact role."
we can write trigger for this i.e when the opportunity is created then opportunityContactRole is also created.

trigger OpportunityTrigger on Opportunity (after insert) {
    
    if(trigger.isAfter && trigger.isInsert){
        set<Id> accountSet=new set<Id>();
        for(Opportunity op:trigger.new){
            accountSet.add(op.accountid);
        }
        List<Contact> contactList=new List<Contact>([select id,accountid from Contact where accountid in: accountSet]);
        List<OpportunityContactRole> ocrList=new List<OpportunityContactRole>();
        for(Opportunity op:trigger.new){
            for(Contact con:contactList){
                 if(op.accountid==con.accountid){
               OpportunityContactRole ocr=new OpportunityContactRole();
                ocr.ContactId=con.id;
                     ocr.OpportunityId=op.id;
                      ocrList.add(ocr);
            }
            }
        }
        if(ocrList.size()>0){
            insert ocrList;
        }
    }
}

Please let me know it is working or not?

if it helps you please mark it as the Best Answer so that other people would take reference from it.
Thank you!

Mita PandyaMita Pandya
Thank you team for your reply. I will try to implement this trigger in my org. Mita
Suraj Tripathi 47Suraj Tripathi 47

ok

please do 

if it works don't forget to mark it as Best.

thank you

John JerryJohn Jerry
When creating a new Opportunity the contact role is automatically populated when the opportunity is created from a contact record(standard functionality). In the case where users create an opportunity from a different record (e.g Account), the opportunity contact role is not automatically populated. https://soundak.com/