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
Ker DeveloperKer Developer 

copying an attachment of a standard object to a custom object - Trigger

Hello, 

 

I have a trigger afterInsert on attachment . When an attachment is created on contact , it is automatically inserted in a custom object . The id of this custom object is referenced in a custom field of the contact . The file is inserted in the custom object . but when i click on "View file " the file is not viewd .In fact the title and the number of KO is mentioned in the file but it is not seen , i dont now why . Here is the apex code : 

public with sharing class MADEL_TR005CreateAttachment 
{
	
	public static void CreerAttachmentOncontactMADEL(List<Attachment> lstattachment)
    {

		Map<Id,Id> mapgetIdcontactMadelfromContact = new Map<Id,Id>();
		Set<Id> contactIds=new Set<Id>();


		for(Attachment att:lstattachment)
		{
			contactIds.add(att.ParentId);
			
			
		}
		
		List<Contact>lstcontacts=[select Id ,idcontactMADEL__c from Contact where Id IN:contactIds ];
		
		
		for(Contact contact:lstcontacts)
		{
			mapgetIdcontactMadelfromContact.put(contact.Id,contact.idcontactMADEL__c);
		}
		List<Attachment>attachtoInsert=new List<Attachment>();
		
	 for(Attachment a:lstattachment)
		{
			Attachment attach=new Attachment(name = a.name, body = a.body, parentid = mapgetIdcontactMadelfromContact.get(a.ParentId));
			attachtoInsert.add(attach);

		}
		insert attachtoInsert;





    }

}

 I really need your Help , Thanks !

 

Alok_NagarroAlok_Nagarro

Hi,

 

You have missed "ContentType" of attachment, without this property server cannot identify the content of file to be open.

In the last loop you need to set also the "contentType" of attchment -

 

for(Attachment a:lstattachment)
        {
            Attachment attach=new Attachment(ContentType = a.ContentType,name = a.name, body = a.body, parentid = mapgetIdcontactMadelfromContact.get(a.ParentId));
            attachtoInsert.add(attach);

        }

Ker DeveloperKer Developer

Hello , 

 

Even if i added this it still doesn't work . The file is not displayed when clicking view File.

 

Please can you help me?