You need to sign in to do that
Don't have an account?
SV M
Count Tasks related to Opportunity
Hi, I have an apex trigger which displays total tasks related to opportunity, but my trigger is not working even it doesn't have any errors. Can someone help me with this trigger?
//Apex Trigger
trigger OpportunityTaskCount on Task (after insert, after update, after delete, after undelete) {
Set<Id> oppList = new Set<Id>();
Set<Id> tskList = new Set<Id>();
List<Opportunity> updateList = new List<Opportunity>();
if(trigger.isInsert) {
for(Task tsk : trigger.new) {
if(tsk.WhatId != NULL) {
oppList.add(tsk.Id);
tskList.add(tsk.WhatId);
}
}
system.debug('Opportunities'+oppList);
}
if(trigger.isDelete || trigger.isUpdate ) {
for(Task tsk : trigger.old) {
if(tsk.WhatId != NULL) {
oppList.add(tsk.Id);
tskList.add(tsk.WhatId);
}
}
}
if(trigger.isUndelete) {
for(Task tsk : trigger.new) {
if(tsk.WhatId != NULL) {
tskList.add(tsk.WhatId);
}
}
}
for (Opportunity opp : [SELECT Id, Name, Total_Tasks__c ,(SELECT Id, Status FROM Tasks)
FROM Opportunity
WHERE Id in : oppList]) {
opp.Total_Tasks__c = opp.Tasks.size();
updateList.add(opp);
}
update updateList;
}
//Apex Trigger
trigger OpportunityTaskCount on Task (after insert, after update, after delete, after undelete) {
Set<Id> oppList = new Set<Id>();
Set<Id> tskList = new Set<Id>();
List<Opportunity> updateList = new List<Opportunity>();
if(trigger.isInsert) {
for(Task tsk : trigger.new) {
if(tsk.WhatId != NULL) {
oppList.add(tsk.Id);
tskList.add(tsk.WhatId);
}
}
system.debug('Opportunities'+oppList);
}
if(trigger.isDelete || trigger.isUpdate ) {
for(Task tsk : trigger.old) {
if(tsk.WhatId != NULL) {
oppList.add(tsk.Id);
tskList.add(tsk.WhatId);
}
}
}
if(trigger.isUndelete) {
for(Task tsk : trigger.new) {
if(tsk.WhatId != NULL) {
tskList.add(tsk.WhatId);
}
}
}
for (Opportunity opp : [SELECT Id, Name, Total_Tasks__c ,(SELECT Id, Status FROM Tasks)
FROM Opportunity
WHERE Id in : oppList]) {
opp.Total_Tasks__c = opp.Tasks.size();
updateList.add(opp);
}
update updateList;
}
--
Magulan Duraipandian
https://www.infallibletechie.com/
All Answers
--
Magulan Duraipandian
https://www.infallibletechie.com/
Please use below code :
Hope this helps you.
If this helps kindly mark it as solved so that it may help others in the future.
Thanks & Regards,
Foram Rana