/** * This class handles the addition of attachments to projects. */ public with sharing class AddAttachementToProjectHandler { //Method to add attachments to a list of projects. public static void AddAttachments(List newProject) { // Collect the Opportunity IDs associated with the new projects try{ Set oppIds = new Set(); for (ProjectDemo__c pro : newProject) { oppIds.add(pro.Opportunity_Name__c); } // Retrieve ContentDocumentLink records for the collected Opportunity IDs List contentDocumentLinks = [ SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN :oppIds ]; // Organize ContentDocumentLinks by Opportunity ID Map> projectIdToContentDocumentLinks = new Map>(); for (ContentDocumentLink cdl : contentDocumentLinks) { List cdlList = projectIdToContentDocumentLinks.containsKey(cdl.LinkedEntityId) ? projectIdToContentDocumentLinks.get(cdl.LinkedEntityId) : new List(); cdlList.add(cdl); projectIdToContentDocumentLinks.put(cdl.LinkedEntityId, cdlList); } // Prepare a list of ContentDocumentLinks to be inserted List insertCdlList = new List(); for (ProjectDemo__c proj : newProject) { system.debug('@@@@@@ proid:'+proj.Id); if (projectIdToContentDocumentLinks.containsKey(proj.Opportunity_Name__c)) { List contentDocumentLinksToCopy = projectIdToContentDocumentLinks.get(proj.Opportunity_Name__c); for (ContentDocumentLink cdl : contentDocumentLinksToCopy) { // Create new ContentDocumentLink records with relevant data ContentDocumentLink newCdl = new ContentDocumentLink( ContentDocumentId = cdl.ContentDocumentId, LinkedEntityId = proj.Id, ShareType = cdl.ShareType, Visibility = cdl.Visibility ); insertCdlList.add(newCdl); } } } // Insert the new ContentDocumentLink records if the list is not empty if (!insertCdlList.isEmpty()) { database.insert(insertCdlList); } } catch(exception ex){ system.debug('Error Occur ==' +ex.getMessage()); } } }