Skip to content

Instantly share code, notes, and snippets.

@srujan21
Created October 17, 2019 16:08
Show Gist options
  • Save srujan21/7a25c2a4a562c2581c484fdac94bf3d8 to your computer and use it in GitHub Desktop.
Save srujan21/7a25c2a4a562c2581c484fdac94bf3d8 to your computer and use it in GitHub Desktop.
Insert Salesforce file and link it to sobject
PageReference pg = Page.EHSC_OSB_PDF;
pg.getParameters().put('id', oppId);
ContentVersion conVer = new ContentVersion();
conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
conVer.PathOnClient = 'OSB '+DateTime.now().getTime()+'.pdf'; // The files name, extension is very important here which will help the file in preview.
conVer.Title = 'OSB '+DateTime.now().getTime()+'.pdf'; // Display name of the files
if(!Test.isRunningTest()){
conVer.VersionData = pg.getContentAsPDF();
}
else{
conVer.VersionData = Blob.valueOf('Appointment Form');
}
insert conVer;
Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId;
//Create ContentDocumentLink
ContentDocumentLink cDe = new ContentDocumentLink();
cDe.ContentDocumentId = conDoc;
cDe.LinkedEntityId = oppId; // you can use objectId,GroupId etc
cDe.ShareType = 'I'; // Inferred permission, checkout description of ContentDocumentLink object for more details
cDe.Visibility = 'AllUsers';
insert cDe;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment