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
mukesh guptamukesh gupta 

Attachment on record

Hi Expert,

I want to add attachment on record creation time in apex code, but in attachment custom code  we need record Id, but record is not created. so how achive this functionality,

Example: when we fill any exam from then we can attachemtn or document, and then save the record.

Thanks
 
Deepali KulshresthaDeepali Kulshrestha
Hi Mukesh,

Yes, you can achieve this functionality by using a trigger. You can use the trigger on sobject you want
to insert an attachment at creation time. In the Below Code, I have use Account as sobject and create a
new text attachment at the time of the creation of account.

And if you want to upload any file then the file should be in your org. You have first upload the file in
documents ----> select any folder you want to upload file ---> then query the file to insert to attachment.

Trigger ==>>>
trigger InsertAttachmentAtRecordCreationTime on Account (after insert) {
    if(trigger.isAfter && trigger.isInsert){
        InsertAttachmentAtRecordCreationTime.insertAccount(trigger.new);
    }
}
Handler Class ==>>
public class InsertAttachmentAtRecordCreationTime {
    public static void insertAccount(List<Account> aclist){
        try{
            List<Attachment>  Attachment_List = new List<Attachment>();
            for(Account ac : aclist){
                Attachment attach = new Attachment();
                attach.Name = String.valueOf('test.txt');
                attach.body = Blob.valueOf('You can give any String Value');
                attach.parentId = ac.Id;
                Attachment_List.add(attach);      
            }
            insert Attachment_List;
        }
        catch(Exception e){
            System.debug('Line No:-->'+e.getLineNumber()+' '+'Error---->'+e.getMessage());
        }
    }
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com