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
Peter BoelkePeter Boelke 

Problem linking contentversion toopportunity

Hello,

i try to "convert" an attachement to a ContentVersion and link it to a related opportunity. Converting works but linking does not!
ia m getting this error message:
FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, You cannot create a link for this type of entity through the api: Linked Entity ID: [LinkedEntityId]

My code is:
trigger TrgAttachment on Attachment (after insert) {
    System.debug('TRG ' + Trigger.New[0]);
    Attachment att = Trigger.New[0];
    //Task t = Trigger.New[0];    
    System.debug('TYPE ' + att.ParentId.getSobjectType());
    Task t = [SELECT Subject, WhatId FROM Task WHERE id=:att.ParentId][0];
    
    System.debug('ATT ' + att);
    if(t.WhatId <> NULL && t.WhatId.getSobjectType() == opportunity.getSObjectType()){

        Opportunity o = [SELECT Id, Name FROM Opportunity WHERE id=:t.WhatId][0];
        System.debug('Related to opps' + o);
        
        ContentVersion cv = new ContentVersion();
        cv.ContentLocation = 'S';
        cv.PathOnClient = att.Name;
        cv.Origin = 'H';
        cv.OwnerId = att.OwnerId;
        cv.Title = att.Name;
        cv.VersionData = att.Body;
        insert cv;
        
        ContentVersion cv1 = [select Id, ContentDocumentId from ContentVersion where Id =: cv.Id][0];
        Id linkDoc = o.Id;
        ContentDocumentLink cl = new ContentDocumentLink();
        cl.LinkedEntityId = linkDoc;
        cl.ContentDocumentId = cv1.ContentDocumentId;
        cl.ShareType = 'V';
        try{
            insert cl;
        }
        catch(Exception ex){
            throw ex;
        }

        
    }
}
Can someone help?

thanks
Peter
 
Best Answer chosen by Peter Boelke
Abhishek BansalAbhishek Bansal
Hi Peter,

Basically you need to query FeedItem object and not the ContentVersion object. You can find the complete solution on the below link:
https://salesforce.stackexchange.com/questions/941/can-you-change-which-records-chatter-files-are-shared-to-through-apex

Please let me know if you need any further help or information on this.

Thanks,
Abhishek Bansal.

 

All Answers

Abhishek BansalAbhishek Bansal
Hi Peter,

Basically you need to query FeedItem object and not the ContentVersion object. You can find the complete solution on the below link:
https://salesforce.stackexchange.com/questions/941/can-you-change-which-records-chatter-files-are-shared-to-through-apex

Please let me know if you need any further help or information on this.

Thanks,
Abhishek Bansal.

 
This was selected as the best answer
Peter BoelkePeter Boelke
This is a really strange solution! I must admit