+ 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: trigger.new) {
            	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: trigger.new) {
            if(opp1.StageName != Trigger.oldMap.get(opp1.id).stageName && taskMap != null && 
               (taskMap.get(opp1.id+Trigger.oldMap.get(opp1.id).stageName).Status != 'Completed'  && 
                taskMap.get(opp1.id+Trigger.oldMap.get(opp1.id).stageName).status != 'Deferred')
               && (taskMap.get(opp1.id+Trigger.oldMap.get(opp1.id).stageName).subject == Trigger.oldMap.get(opp1.id).stageName)
              ) {
                   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".