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
Benjamin Zerbib 3Benjamin Zerbib 3 

number of task per opportunity

Hey Everybody!

I need some help for something:
I would like to know the number of Tasks per Opportunity so I could delete the first one when the number of Tasks is superior to 1.

I haven't developed any trigger before... Could somebody help me please?

Thanks in advance!

Ben
VinayVinay (Salesforce Developers) 
Hi Benjamin,

Try below snippet.
trigger CountTask on Task (after insert, after update) {
    
    public List<Task> ltask1 = new List<Task>();
    public id oppid;
    public integer inp=0;   
    public integer inr=0;
    for(Task t:Trigger.New){
        oppid = t.WhatId;
        system.debug('oppid'+oppid);
        
    }
	ltask1 = [select id,Status from task where whatid=:oppid];
    system.debug('oppsize'+ltask1.size());
    
    
    for(task t:ltask1){
        if(t.Status!='Completed'){
            inp = inp+1;
        } else{
            inr = inr +1;
        }                
    }
    List<Opportunity> opp = new List<opportunity>();	
    List<opportunity> op = [select id from Opportunity where id = :oppid];
    system.debug('oppsize'+op.size());
    for(opportunity o: op){
        o.Open_Tasks__c = inp;
        o.Closed_Tasks__c = inr;
        opp.add(o);  
    }
    if(opp.size()>0){
    	update opp;
	}        
           
}

Also, try to check if you can use the formula field.

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar