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
CushtyCushty 

trigger to add contact as contact role when creating opp on contact

Hi,

When an opportunity is created from a contact, I want this contact to them become the contact role on that opportunity.

I know this is standard functionality in salesforce but I have to created a custom button to create a new opportunity as it updates a few fields so lost this functionality......unless there is an easier way to keep the origional New button and then default some fields before the report is created?

Thanks
Best Answer chosen by Cushty
RudrarajuRudraraju
In that case create a lookup to contact or text field in opportunity and pass the contact id to that field in custom button URL from contact. Then write a trigger for after Insert and create OpportunityContactRole using the field we created for contact id

All Answers

RudrarajuRudraraju
I think it is better to create OpportunityContactRole when Opportunity is created through Contact.

Sample Code 

Opp.Name = 'Opportunity Name'';
Opp.StageName = 'Interest';
Opp.AccountId = Contact.AccountId;
Opp.CloseDate = System.Today().addDays(30);
Insert Opp;
          
OpportunityContactRole CntRole = New OpportunityContactRole();
CntRole.ContactId = Contact.Id;
CntRole.OpportunityId = Opp.Id;
Insert CntRole; 
CushtyCushty
Yes that is what I am trying to achieve.  I know it is standard salesforce functionality but I no longer use the New button on opportunities so need the apex code to create the contact role when an opportunity is created through a contact
RudrarajuRudraraju
In that case create a lookup to contact or text field in opportunity and pass the contact id to that field in custom button URL from contact. Then write a trigger for after Insert and create OpportunityContactRole using the field we created for contact id
This was selected as the best answer
CushtyCushty
Thanks, didn;t think of that as an idea.
I created the lookup field and passed it in my button, then created a flow and process to create the contact role