+ Start a Discussion
Jan Kopejtko 2Jan Kopejtko 2 

Automatically add a file to a record upon creation

Hey guys,

I have object A.

I have let's say a PDF or a Word file I want to attach automatically. to each record of object A upon creation.

I don't see how process builder could do this, so is there a way to do this? Maybe in apex? Thanks
Soyab HussainSoyab Hussain
Hi Jan Kopejtko,

First, you have to insert your file in static recourse, I have an example see this.

Create a trigger which object you want, I created on the account.

Trigger Code:
trigger AccountTrigger on Account (after insert) {
    if(Trigger.isInsert && Trigger.isAfter){
        List<Attachment> attachments = new List<Attachment>();

        // Query static resource file
        List<StaticResource> file = [Select body, name from StaticResource where Name = 'DemoPDF'];
        if( file.isEmpty() ) {
        for(Account acc : Trigger.New) {
                new Attachment(Name = 'Doc File', Body = file[0].Body, ParentId = acc.Id, Description = 'Description') 
        // insert attachments
        if( !attachments.isEmpty() ) {
            insert attachments;

If you found it useful please appreciate my efforts and mark it as the best answer.

LinkedIn:  https://www.linkedin.com/in/soyab-hussain-b380b1194/

satish palsatish pal
Hi Jan,
This is possible via apex, save your PDF in the document folder
then create a trigger on Object A for after insert event and paste the below code:

document attach=[SELECT Id, BodyLength, Body,name, Type FROM Document where id='01590000000A6CgAAK'];  // Document Id

ContentVersion v = new ContentVersion();
            v.versionData = attach.body;
            v.title = attach.name;
            v.pathOnClient =attach.Type;
            insert v;
            ContentDocumentLink cDe = new ContentDocumentLink();
            cDe.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: v.id].ContentDocumentId;
            cDe.LinkedEntityId = '0039000000sjmbJAAQ';   // Object A Id
            cDe.ShareType = 'I'; 
            insert cDe;

Satish Pal