public class CopyAttachmentHandler { public static void copyAtt(ListpdList){ try{ //releted opp id Set OppId = new Set(); Set CdId = new Set(); // related attachment id of opp id Set attId = new Set(); for(ProjectDemo__c pd1:pdList){ OppId.add(pd1.Opportunity_Name__c); } System.debug('@@@@@@ oppid'+OppId); for(ContentDocumentLink ac:[SELECT Id,ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId IN:OppId]){ attId.add(ac.Id); CdId.add(ac.ContentDocumentId); } System.debug('@@@@@@ Attid'+attId); System.debug('@@@@@@ CdId'+CdId); list newContentVersion=new list(); list cdl=new list(); List attachmentList = [SELECT Id, VersionData,Description, Title, ContentBodyId, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN:CdId]; System.debug('@@@@@@ attachmentList'+attachmentList); for(ContentVersion att: attachmentList) { ContentVersion newFile = new ContentVersion(); newFile.Title = att.Title; newFile.ContentBodyId = att.ContentBodyId; newFile.Description=att.Description; newContentVersion.add(newFile); } insert newContentVersion; List CdIdid = new List(); for(ContentVersion cvv:newContentVersion){ CdIdid.add(cvv.ContentDocumentId); } System.debug('@@@@@@ new content documnet id'+CdIdid); for(ProjectDemo__c pd:pdList){ ContentDocumentLink newLink= new ContentDocumentLink(); newLink.LinkedEntityId=pd.Id; for(Id ccd:CdIdid){ newLink.ContentDocumentId=ccd; } cdl.add(newLink); } insert cdl; } catch(Exception e){ system.debug('@@@@ Error'+e); } } }