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
Diarmuid O'Shea 9Diarmuid O'Shea 9 

Adding Files to Objects

Good Afternoon,

I am hoping soeone may be able to advise on best practise. Each day a number of new 'files' are added to our insance of salesforce  , these are related to specfic accounts. Is there a way using a trigger or flows of auotmaically adding these to the relevant account if it can be identidied via the file name.

Many Thanks
AnudeepAnudeep (Salesforce Developers) 
If you want to do it automatically, I suggest doing it with a trigger. Here is a sample code
//Get attachment
Attachment attach = [SELECT Id, Name, Body, ContentType, ParentId From Attachment LIMIT 1];
 
//Insert ContentVersion
ContentVersion cVersion = new ContentVersion();
cVersion.ContentLocation = 'S'; //S-Document is in Salesforce. E-Document is outside of Salesforce. L-Document is on a Social Netork.
cVersion.PathOnClient = attach.Name;//File name with extention
cVersion.Origin = 'H';//C-Content Origin. H-Chatter Origin.
cVersion.OwnerId = attach.OwnerId;//Owner of the file
cVersion.Title = attach.Name;//Name of the file
cVersion.VersionData = attach.Body;//File content
Insert cVersion;
 
//After saved the Content Verison, get the ContentDocumentId
Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;
 
//Insert ContentDocumentLink
ContentDocumentLink cDocLink = new ContentDocumentLink();
cDocLink.ContentDocumentId = conDocument;//Add ContentDocumentId
cDocLink.LinkedEntityId = attach.ParentId;//Add attachment parentId
cDocLink.ShareType = 'I';//V - Viewer permission. C - Collaborator permission. I - Inferred permission.
cDocLink.Visibility = 'InternalUsers';//AllUsers, InternalUsers, SharedUsers
Insert cDocLink;

Another recommendation is to do a mass upload specifying the parentId using data loader 

https://developer.salesforce.com/docs/atlas.en-us.dataLoader.meta/dataLoader/loader_attachments.htm

Let me know if this helps, if it does, please close the query by marking it as solved. It may help others in the community. Thank You!
Ramprasad VarriRamprasad Varri
Relying on file name is bad idea. But yes you can associate a file with a record by creating a trigger on content document. In the trigger create a record in Content Document Link, sharing the file with the account ( which is determined using the name).