+ Start a Discussion
sudha76sudha76 

Trigger on Parent Object to check if the attachment is provided or not.

Hi there,

 

Can we create a TRIGGER on a custom object , that will make sure an attachment is provided under the notes and attachment section, before the record is saved.?

 

Is this possible?

 

thanks

 

Starz26Starz26

This would only be possible for editing a record. You cannot have an attachment unless the parent already exists.

 

This class will return the number of attachments and you can process as you need

 

public class checkAttachments{

public static boolean isInsert = false;
public static Map<ID,integer> numberOf(SObject[] obj){
           AggregateResult[] att = [Select count(ID)cnt, ParentID From Attachment Where ParentID IN :obj GROUP BY ParentID ];
          
          Map<ID,Integer> mOfAttachmentCount = New Map<ID,Integer>();

          for(AggregateResult a : att){

              mOfAttachmentCount.put((String)a.get('ParentID'),(Integer)a.get('cnt'));

          }

          
          for(SOBject o : obj){

              if(!mOfAttachmentCount.containsKey(o.id))
                  mOfAttachmentCount.put(o.id,0);

          }

          return mOfAttachmentCount;

      }

}

 

From your trigger pass in the trigger.new object from a before update trigger event.

 

**On the insert event call checkAttachments.isInsert = true. Then check for the checkAttachments.isInsert == false in your trigger to add error. This will prevent the insert from failing when workflows fire off the update event (if you have them)