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
AbhisreeAbhisree 

Can't create new ContentDocumentLink

We have a custom inbound email service that attaches inbound emails as attachments to certain objects. I'm trying to change the code to create a file instead but get an error when trying to create a new ContentDocumentLink to attach the document to the object. Thanks in Advance.

Error: Invalid type:ContentDocumentLink
Error: DML requires SObject or SObject List Type: ContentDocumentLink

I think my content settings are correct.

Code snippet for reference:

else
{
ContentVersion conVer = new ContentVersion();
Long sz;

if(email.subject.length()>80)
{

conVer.Title= email.subject.substring(0,80);
}
else
{

conVer.Title= email.subject;
}
conVer.PathOnClient =conVer.Title+'.pdf';
if(email.plainTextBody == null)
{
conVer.VersionData = blob.valueof(email.htmlBody);
sz = email.htmlBody.length();
}
else
{
conVer.VersionData = blob.valueof(email.plainTextBody);
sz = email.plainTextBody.length();
}
insert conVer;
Id condId=conVer.ContentDocumentId;

ContentDocumentLink cdl = New ContentDocumentLink(LinkedEntityId = book.id, ContentDocumentId = condId, shareType = 'I');
insert cdl;
Ryan GreeneRyan Greene
ContentDocumentLink is more like a junction object, you're not going to be able to directly add the Document to the ContentDocLink object: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocumentlink.htm
I think you'll also need to create a ContentDocument: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocument.htm
That's where you'd load the attachment
Or to make this process even easier, just use the Attachment object, then no need for multiple objects like you're using. There are some downfalls to using just Attachment so I can see why you would want to use the Content Docs.
This is how I attach a document to a custom object:
Document__c doc = new Document__c();
            doc.Document__c = 'Final PDF';
            doc.Opportunity__c = ld[0].ConvertedOpportunityId;
        	doc.RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Attach' AND SobjectType = 'Document__c' LIMIT 1].Id;
            insert doc;
            
            Attachment attachment = new Attachment();
            attachment.body = pdfBody;
            attachment.name = 'Final Lead PDF.pdf';
            attachment.parentId = doc.Id;
            insert attachment;