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
Sachin Chaudhary 15Sachin Chaudhary 15 

Not Allow to change Opportunity Stage if previous stage has open tasks


The system should not allow me to change the Opportunity stage if the previous opportunity's stage related task is not completed.Task status should be equal to complete.

Hi Sachin,
Write Before Trigger on Opportunity and take count by query in that where condition would be taskstatus = "open"..
if count is greater than 1 then addError that "some tasks are already open"
NagendraNagendra (Salesforce Developers) 
Hi Sachin,

please find updated code below  which will work for both New and Update Opportunity:
Trigger TaskCreation on Opportunity (after insert, after update) {
    List<Task> taskToInsert = new list<Task>();
    if(trigger.isInsert && Trigger.isAfter){
        for(Opportunity opp: {
            	Task objTask = new Task();
                objTask.whatId = opp.Id;
                objTask.subject = opp.StageName;
    if(trigger.isUpdate && Trigger.isAfter){
        system.debug(' in after update:');
        taskToInsert = new list<Task>();
        Map<String, Task> taskMap = new map<String, Task>();
        for(Task t: [select id, subject,whatId, status from Task where whatId IN :trigger.newMap.keyset()]){
            taskMap.put(t.whatId+t.subject, t);
        if(taskmap != null)
        	system.debug('task map: '+ taskMap.values()); 
        for(Opportunity opp1: {
            if(opp1.StageName != Trigger.oldMap.get( && taskMap != null && 
               (taskMap.get( != 'Completed'  && 
                taskMap.get( != 'Deferred')
               && (taskMap.get( == Trigger.oldMap.get(
              ) {
                   opp1.addError(' Task related to this Opportunity is still in progress');
                   Task objTask = new Task();
                   objTask.whatId = opp1.Id;
                   objTask.subject = opp1.StageName;
        insert taskToInsert ;

Hope this helps.

Please mark this as solved if the information helps so that it gets removed from the unanswered queue which results in helping others who are encountering similar issue.

Best Regards,

Sachin Chaudhary 15Sachin Chaudhary 15

Hi Prithviraj and Nagendra,
I tried what you explained Prithviraj but didnt get my output.
and Nagendra, your code working fine whenever I am creating and updating opportunity record, but when some of my record gets updated by approval process then its giving error "Attempt to de-reference a null object".