+ Start a Discussion
SFTerrSFTerr 

trigger works only when creating new record, not after update

I have a trigger which populates custom opportunioty field (Primary_Contact_Role__c) with the name of the contact selected as primary which works great when new record is being created. How can I modify it, so the name of the contact is changed if user selects different primary contact on the same opportunity?
 
trigger PrimaryContactRole on Opportunity (before update) {

List<OpportunityContactRole> cRoles = new List<OpportunityContactRole>();

cRoles = [SELECT OpportunityId, IsPrimary, Contact.Name FROM OpportunityContactRole WHERE OpportunityId IN :Trigger.newMap.keySet() AND IsPrimary = TRUE];
    for(OpportunityContactRole ocr : cRoles) {
        Trigger.newMap.get(ocr.OpportunityId).Primary_Contact_Role__c = ocr.Contact.Name;
    }
}
Thank you in advance
 
Chamil MadusankaChamil Madusanka
You need to defined the trigger context in the trigger (after update) initiation as follows.
 
trigger PrimaryContactRole on Opportunity (after update, before update)

 
SFTerrSFTerr
And will I need to modify the code so it will include:
if(trigger.isBefore){...}
if(trigger.isAfter){...}
or is it just a simple matter of changing the 1st line to:
trigger PrimaryContactRole on Opportunity (before update,after update) {
?

 
SFTerrSFTerr
Hi Chamil, when you have a chance, will you please have a look at the code below?
When I'm changing primary contact role onm opportunity I get error:  "PrimaryContactRole: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.PrimaryContactRole: line 17, column 1" 
 
trigger PrimaryContactRole on Opportunity (before update,after update) {

if(trigger.isBefore){
List<OpportunityContactRole> cRoles = new List<OpportunityContactRole>();

cRoles = [SELECT OpportunityId, IsPrimary, Contact.Name FROM OpportunityContactRole WHERE OpportunityId IN :Trigger.newMap.keySet() AND IsPrimary = TRUE];
    for(OpportunityContactRole ocr : cRoles) {
        Trigger.newMap.get(ocr.OpportunityId).Primary_Contact_Role__c = ocr.Contact.Name;
}
}
    
if(trigger.isAfter){    
List<OpportunityContactRole> cRoles = old List<OpportunityContactRole>();

cRoles = [SELECT OpportunityId, IsPrimary, Contact.Name FROM OpportunityContactRole WHERE OpportunityId IN :Trigger.oldMap.keySet() AND IsPrimary = TRUE];
    for(OpportunityContactRole ocr : cRoles) {
        Trigger.oldMap.get(ocr.OpportunityId).Primary_Contact_Role__c = ocr.Contact.Name;
}   
}
}
row 17 is:         Trigger.oldMap.get(ocr.OpportunityId).Primary_Contact_Role__c = ocr.Contact.Name;