trigger CountAttachment on Attachment (after insert, after update, after delete, after undelete) {
// Contains the IDs of all the parent tasks
Set<Id> parentTaskIdSet = new Set<id>();
if (trigger.new != null)
{
for (Attachment a: trigger.new)
{
parentTaskIdSet.add(a.parentId);
}
}
if (trigger.old != null)
{
for (Attachment a: trigger.old)
{
parentTaskIdSet.add(a.parentId);
}
}
// List of tasks that needs to be updated
List<Task> parentTaskList = [SELECT id, (SELECT id FROM Attachments) FROM Task WHERE id in: parentTaskIdSet];
for (Task t: parentTaskList)
{
t.NumberOfAttachments__c = t.Attachments.size();
}
update parentTaskList;
}
-----------------------------------------------------------------------------
-------------------------------------------------------------------------------
trigger UpdateAttachmentCount on Task (after insert, after update) {
if (checkRecursive.runOnce())
{
List<Task> taskList = new List<Task>();
Set<ID> taskIDSet = new Set<ID>();
if (trigger.old != null)
{
for (Task t: trigger.old)
{
taskIDSet.add(t.ID);
}
}
if (trigger.new != null)
{
for (Task t: trigger.new)
{
taskIDSet.add(t.ID);
}
}
// Query for the attachment children of the tasks
taskList = [SELECT id, (SELECT id FROM attachments) FROM Task WHERE ID in: taskIDSet];
for (Task t: taskList)
{
t.NumberOfAttachments__c = t.Attachments.size();
}
update taskList;
}
-----------------------------------------------------------------------------
------------------------------------------------------------------------------
public Class checkRecursive{
private static boolean run = true;
public static boolean runOnce(){
if (run){
run = false;
return true;
}
else
{
return run;
}
}
}
Excellent information with unique content and it is very useful to know about the information based on blogs Salesforce Training and Placement | Salesforce Developer Training
ReplyDeleteWhy we need check Trigger.old value in Task Trigger (after update, after insert).
ReplyDeleteTrigger.new value not enought?