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
DevelopementDevelopement 

Trigger Delete help

Hi,

Hello,

I have this Trigger that update the checkbox to true if an Opp has an attachment. and update the checkbox to false if I delete the attachment. This Trigger work fine.

 

But if Opp has 3 attachment and if I delete the one attachment it update the checkbox to false. How should I modify this trigger so it should update the checkbox to false only if there is no attachment

 

trigger Att_Aft_Trig on Attachment (after insert, after update,after delete)
{
if(trigger.isInsert || trigger.isUpdate){
List<Opportunity> co = [select id, Attachement__c from Opportunity where id =: Trigger.New[0].ParentId];
if(co.size()>0)
{
co[0].Attachement__c = true;
update co;
}
}
if(trigger.isDelete){
List<Opportunity> co1 = [select id, Attachement__c from Opportunity where id =: Trigger.old[0].ParentId];
if(co1.size()>0)
{
co1[0].Attachement__c = false;
update co1;
}

}
}

AdamDawAdamDaw

I would probably do something like this:

 

trigger Att_Aft_Trig on Attachment (after insert, after update, after delete){

  Set<Id> oppIds = new Set<Id>();
  if(trigger.isInsert || trigger.isUpdate){
    for(Attachment att : trigger.new){
      if(att.ParentId.getSObjectType().getDescribe().getName() == 'Opportunity'){
        oppIds.add(att.ParentId);
      }
    }
  }
  if(oppIds.size() > 0){
    OpportunityUtils.checkAttachmentStatus(oppIds);
  }

}

public class OpportunityUtils{

  @future
  public static void checkAttachmentStatus(Set<Id> oppIds){
    List<Opportunity> opps = [Select Id, Attachement__c, (Select Id from Attachments) from Opportunity where Id in :oppIds];
    for(Opportunity opp : opps){
      opp.Attachement__c = (opp.Attachments.size() > 0);
    }
    update opps;
  }


}

 Best,

Adam

 

sfdcfoxsfdcfox
trigger X on attachment (after insert, after update, after delete) {
    map<id, opportunity> records = new map<id, opportunity>();
    for(attachment record: trigger.new == null? trigger.old: trigger.new)
        if(record.parentid.getsobjecttype() == opportunity.sobjecttype)
            records.put(record.parentid, new opportunity(id=record.parentid, hasattachments__c=!trigger.isdelete));
	if(Trigger.isdelete)
		for(Attachment record:[SELECT Id, ParentId FROM Attachment WHERE ParentId IN :records.keySet()])
			records.get(record.parentid).hasattachments__c = true;
	update records.values();
}