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
Jack A 2Jack A 2 

Trigger is not working?

I am trying to write a trigger that will copy the same attachment to all related contact when we insert an attachment to Account Object.
trigger CopyAttachmentsToCon on Attachment (after insert) {

    Set<Id> AccountIds = new Set<Id>();
    for(Attachment file : Trigger.new) {
     
        if(file.ParentId.getSObjectType() == Account.getSObjectType()) {
            AccountIds.add(file.ParentId);
        }
    }
Now how to get map of all the related contact of coresponding Account with Attachment?
 
swati_sehrawatswati_sehrawat
Use code something like below;
 
trigger CopyAttachmentsToCon on Attachment (after insert) {

    Set<Id> AccountIds = new Set<Id>();
    for(Attachment file : Trigger.new) {
     
        if(file.ParentId.getSObjectType() == Account.getSObjectType()) {
            AccountIds.add(file.ParentId);
        }
    }
	
	if(AccountIds!=null && !AccountIds.isEmpty()){
		list<contact> tempList = [select id from contact where id in : AccountIds];
		if(tempList!=null && !tempList.isEmpty()){
			for(contact con : tempList){
				Attachment obj = new Attachment();
				obj.ParentId = con.id;
			}
			 
		}
	}

 
Rupal KumarRupal Kumar
Hi,
 Try this code-
Trigger CopyAttachmentsToCon on Attachment(after insert) {

      Set < Id > AccountIds = new Set < Id > ();
      Map < String, List < Attachment >> accountIDvsAttachmentList = new Map < String, List < Attachment >> ();
      for (Attachment file: Trigger.new) {

       if (file.ParentId.getSObjectType() == Account.getSObjectType()) {
        AccountIds.add(file.ParentId);

        //Adding attachment to Map
        if (accountIDvsAttachmentList.containsKey(file.ParentId)) {
         (accountIDvsAttachmentList.get(file.ParentID)).add(file);
        } else {
         accountIDvsAttachmentList.put(file.ParentID, new List < Attachment > {
          file
         });

        }

       }
      }
      if (AccountIds != null && !AccountIds.isEmpty()) {
       //Query wrt AccountID and not id
       list < contact > tempList = [select id, AccountID from contact where AccountID in : AccountIds];
       List < Attachment > attachmentsToBeInserted = new List < Attachment > ();
       if (tempList != null && !tempList.isEmpty()) {
        for (contact con: tempList) {
         if (accountIDvsAttachmentList.containsKey(con.AccountID)) {
          for (Attachment attached: accountIDvsAttachmentList.get(con.AccountID)) {

           Attachment obj = new Attachment();
           obj.ParentId = con.id;
           obj.body = attached.body;
           obj.name = attached.name;
           attachmentsToBeInserted.add(obj);
          }
         }
        }
        insert attachmentsToBeInserted;

       }
      }
}

Thank
Rupal kumar
http://mirketa.com