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
Nathan Prats 22Nathan Prats 22 

Trigger validation rule on opportunity

Hello, 

I'm trying to force our sales reps to fill a primary contact on opportunities before they change the opportunity to the stage "Won by Sales". 
I created this trigger on opportunity but it doesn't work.
 
I receive this error : You encountered some errors when trying to save this record
There's a problem saving this record. You might not have permission to edit it, or it might have been deleted or archived. Contact your administrator for help.


I think I need some kind of map but I can't figure it out. Any idea ? 
 
trigger OpportunityTriggers on Opportunity (before delete, before insert, before update,after delete, after insert, after update) {
    
    if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
        
        For (Opportunity o : [SELECT Id,
                              (select ContactId from OpportunityContactRoles where IsPrimary=true LIMIT 1)
                              FROM Opportunity
                              WHERE StageName='Won by Sales']
            ) 
        {
            
            if (o.OpportunityContactRoles.size() != 1){
                o.addError(System.Label.Missing_Primary_Contact);                                     
            }
        }
    }
}
Nathan
 
Steven NsubugaSteven Nsubuga
Are you doing this in a sandbox? Try recreating it, might be a weird quirk, maybe sign out and sign in again and try creating it once more.