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
Jay Parikh 36Jay Parikh 36 

Inserting contactrole on opp creation but getting error:

Here is a trigger :
trigger ContactroleonOpp on Opportunity (after insert) {
  list <OpportunityContactRole > i = new list <OpportunityContactRole >();
  
  for(Opportunity  newopp : trigger.new){
    if (newopp.id != null ){
      i.add(new OpportunityContactRole (
       OpportunityId = newopp.id,
       //accountname = newopp.AccountId,
       ContactId = newopp.AccountId,
       Role = 'Other', 
       IsPrimary = true));
    
    
    }
  }
  
  insert i ;
  }

Error msg:Review all error messages below to correct your data.
Apex trigger ContactroleonOpp caused an unexpected exception, contact your administrator: ContactroleonOpp: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Contact ID: id value of incorrect type: 
Dev_AryaDev_Arya
for contactID, shouldn't it be a contactID instead of AccountID?
Jay Parikh 36Jay Parikh 36
I am using personal account and Opportunity there is only one field which is Account name and also on OpportunityContactRole object there is no such field called accountname .
Dev_AryaDev_Arya
in that case use
 ContactId = newopp.Account.PersonContactId;
But then in any case if you also have non Personal Accounts associated to the Opportunity, then you need to change th logic in your trigger to handle such cases and make appropriate checks.

If this helps, please mark the solution green.
Cheers,Dev