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
Amol Jadhav 9Amol Jadhav 9 

Apex Trigger On Opportunity

I have Created Trigger on Opportunity which displays error message to the user if there is open task on Opportunity and user try to change the Stage value. It is working fine for this scenario but not for other if there is no open task present on opportunity and user try to change stage value and save the record it shows error as,

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Please Close Open Activities to update...".

Trigger is As
------------------------
trigger ShowErrorMsgOnOpportunity on Opportunity (before insert, before update) {

    List<Opportunity> newOppo = Trigger.new;
    
    try{
        List<Opportunity> countOpenTask = 
        [Select Id, Name, (Select Id, Status, WhoId From OpenActivities Where Status != 'Completed')OppoTask From Opportunity where Id IN: Trigger.new];
       
        for(Opportunity op : countOpenTask){
            if(op.OpenActivities.size() != 0){
              Trigger.newMap.get(op.Id).addError('Please Close Open Activities to update...');
            }   
        }
     }
     catch(Exception excep)
     {
         System.debug('Error='+excep);
     }  
}
Best Answer chosen by Amol Jadhav 9
kkgkkg
Hi Amol Jadhav,

I have used the same trigger in my org and the trigger is working fine as expected in my org. I think trigger is working good.Please check validation rules on oppty.

Note. if there is no open task present on opportunity and the user try to change stage value and save the record with out an error..