+ Start a Discussion
Matt MetrosMatt Metros 

Creating Opportunity and OpportunityContactRole in Apex Trigger

public with sharing class InsertPreOpportunity {
	public static void handleTrigger(List<Form__c> newForms) 
	{
		// check if this is a demo set form

		Map<Id, Opportunity> contact_With_pre_Opptys_to_Insert = new Map<Id, Opportunity>();

		for(Form__c form: newForms)
		{

			if(form.RecordType.Name == 'Demo Set Form')
			{
				Opportunity preOppty = new Opportunity(
					OwnerId			= form.AE_Owner__c,
					AccountId	 	= form.Account__c,
					SDR_Owner__c 	= form.SDR_Owner__c,
					SDR_Notes__C 	= form.SDR_Notes__c,
					LinkedIn_URL__c = form.LinkedIn_URL__c,
					ERP_Systems__c 	= form.ERP_Systems__c,
					RecordTypeId	= '0126A000000yudDQAQ',
					Estimated_Annual_Spend__c = form.Estimated_Annual_Spend__c
				);


				contact_With_pre_Opptys_to_Insert.put(form.Contact__c, preOppty);



			}
		}


		for(ID con: contact_With_pre_Opptys_to_Insert.keySet())
		{
			Opportunity opp = contact_With_pre_Opptys_to_Insert.get(con) ;

			OpportunityContactRole oppConRole = new OpportunityContactRole(
				OpportunityId 	= opp.Id,
				ContactId		= con,
				isPrimary		= true

			);
		}

	}
}

Hi, Do I need to insert the opportunities before I insert opportunitycontactroles? Or will the code above work.
Maharajan CMaharajan C
Hi Matt,

Yes first you have to insert the opportunity in database there after only you can acessa the opportunity Id to insert the opportunity contact role record.

Thanks 
MahaRajan.C
Maharajan CMaharajan C
Better write the trigger in Opportunity object at after insert transaction for insert the opportunity contact role record