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
AprilVAprilV 

Need Help with Trigger - Field update on Contract Record

Hello,

 

I am trying to create a trigger on the Contract record that will update 2 email fields on the contract record from fields on the releated opportunity record.

 

Here is my code:

trigger UpdateContractEmails on Contract (before insert, before update, after insert, after update){ 

for (Contract c : trigger.new){

   Opportunity opp = [SELECT Id FROM Opportunity WHERE Id = :c.Opportunity__c]; 
   
c.Account_Manager_Email__c = opp.Account_Manager_Email__c;
c.Account_Executive_Email__c = opp.Account_Executive_Email__c;
update c;

}
}

 

And here is the error I am getting on the record when I am trying to save:

 

Apex trigger UpdateContractEmails caused an unexpected exception, contact your administrator: UpdateContractEmails: execution of BeforeInsert caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Opportunity.Account_Manager_Email__c: Trigger.UpdateContractEmails: line 7, column 30

 

Any ideas on what changes I need to make to the code to make this work? I would use a formula field to port this info over, but I need these fileds to be filed type email address so I can use them in an email alert.

 

Thanks!

steve456steve456

you cannot do this way...First pull the list of  id for bulk process...Map the id of the correspondng fields ......then do the update

steve456steve456

dont perfom soql inside for loops

cashworthcashworth

You might give this a whirl...

 

trigger UpdateContractEmails on Contract (before insert, before update, after insert, after update){ 

//You need to query the fields from the Opp where you want to pass the values to the Contract

List<Opportunity> opp = [SELECT Id,Account_Manager_Email__c, Account_Executive_Email__c FROM Opportunity WHERE Id = :trigger.new[0].Opportunity__c LIMIT 1]; 


//change the for loop to an if statement and check that the list has a value
if (opp.size() > 0){

   
  c.Account_Manager_Email__c = opp.Account_Manager_Email__c;
  c.Account_Executive_Email__c = opp.Account_Executive_Email__c;

// you do not need an update statement to change field values on a trigger for the object that is in focus
//  update c;

}
}

 

cashworthcashworth

One more thing I just noticed is you are specifying this trigger to run after insert and after update. Those need to be removed as the record will be read only in an "after" trigger situation.