+ Start a Discussion
Eduardo AndradeEduardo Andrade 

Generate ContentDistribution external link from Apex

Hi, I can query on ContentDistribution the url of a file that I manually shared with external.

Is it possible to generate that url from Apex?

Thanks

Best Answer chosen by Eduardo Andrade
Eduardo AndradeEduardo Andrade
This way it worked, I can assign the ContentVersionId rather than ContentDocumentId.
 
ContentDocumentLink cdl = [select contentdocument.id, contentdocument.title, contentdocument.filetype from contentdocumentlink where linkedentityid = '<Opportunity Id>'];
ContentVersion cv = [select id from contentversion where contentdocumentid = :cdl.contentdocument.id];
ContentDistribution cd = new ContentDistribution();
cd.Name = 'Test';
cd.ContentVersionId = cv.id;
cd.PreferencesAllowViewInBrowser= true;
cd.PreferencesLinkLatestVersion=true;
cd.PreferencesNotifyOnVisit=false;
cd.PreferencesPasswordRequired=false;
cd.PreferencesAllowOriginalDownload= true;
insert cd;

 

All Answers

Abhishek BansalAbhishek Bansal
Hi Eduardo,

Yes, it is possible to generate the URL from the apex class since update() is a supported call for the ContentDistribution object. You can find the complete information about this object and its fields in the link given below:
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdistribution.htm

Please let me know if you need any other helpm on this.

Thanks,
Abhishek Bansal.
Eduardo AndradeEduardo Andrade
Thanks Abhishek, but I've tried this code bellow and got the error: "the ContentDocumentId field is not writeable". It must have another way to create the link?
 
ContentDocumentLink cdl = [select contentdocument.id, contentdocument.title, contentdocument.filetype from contentdocumentlink where linkedentityid = '<Opportunity Id>'];

ContentDistribution cd = new ContentDistribution();
cd.ContentDocumentId = cdl.contentdocument.id;
insert cd;

 
Eduardo AndradeEduardo Andrade
This way it worked, I can assign the ContentVersionId rather than ContentDocumentId.
 
ContentDocumentLink cdl = [select contentdocument.id, contentdocument.title, contentdocument.filetype from contentdocumentlink where linkedentityid = '<Opportunity Id>'];
ContentVersion cv = [select id from contentversion where contentdocumentid = :cdl.contentdocument.id];
ContentDistribution cd = new ContentDistribution();
cd.Name = 'Test';
cd.ContentVersionId = cv.id;
cd.PreferencesAllowViewInBrowser= true;
cd.PreferencesLinkLatestVersion=true;
cd.PreferencesNotifyOnVisit=false;
cd.PreferencesPasswordRequired=false;
cd.PreferencesAllowOriginalDownload= true;
insert cd;

 
This was selected as the best answer
mhamzasmhamzas
Thanks @Eduardo Andrade,

I've compiled all the info I got here for others:
https://www.mhamzas.com/blog/2020/01/09/use-salesforce-files-image-file-on-lwc-aura-or-vf-page-as-tag/