+ Start a Discussion
Peter BölkePeter Bölke 

Trigger on Opportunity / Files


we need a trigger which executes when a file is uploaded to opportunity. File needs to be linked to the account which is related to the opportunity.
Want to check the LinkedEntityId of the ContentDocumentLink created by the upload if its an Opportunity or nor. The problem is that LinkedEntityId includes the id of the uploading user but not the of the opportunity to which the file is uploaded.

But i need the opportunity-id.

My Trigger runs on ContentVersion and uses following helper:
public class TrgContentVersionHelper {
    public void updateAccountFiles(List<ContentVersion> lcv){
        System.debug('TrgContentVersionHelper UPDATE:: ' + lcv);
    public void insertAccountFiles(List<ContentVersion> lcv){
        System.debug('TrgContentVersionHelper INSERT:: '+lcv);
        Set<Id> contentDocumentIdSet = new Set<Id>();
        for(ContentVersion cv:lcv)
            if(cv.ContentDocumentId != null)
        ContentDocumentLink cd = [SELECT ContentDocumentId, LinkedEntityId, ShareType FROM ContentDocumentLink WHERE ContentDocumentId = :lcv[0].ContentDocumentId Limit 1];
        id checkId = cd.LinkedEntityId;
        Map<Id, ContentVersion> historyMap = new Map<Id, ContentVersion>(lcv);
        System.debug('HI '+ historyMap);
        if(checkId.getSobjectType() == Opportunity.sObjectType){
            System.debug('Links ' + cd);
            List<ContentDocumentLink> cdl = new List<ContentDocumentLink>();

                Opportunity lOp = [SELECT Id, AccountId From Opportunity WHERE Id =:cd.LinkedEntityId][0];
                List<ContentVersion> cvList = [SELECT Id, ContentDocumentId FROM ContentVersion where Id IN: historyMap.keySet()];
                for(ContentVersion cv:cvList)
                    if(lOp != Null)
                        ContentDocumentLink c = new ContentDocumentLink();
                        c.ContentDocumentId = cd.ContentDocumentId;
                        c.LinkedEntityId = lOp.AccountId;
                        c.ShareType = cd.ShareType;
                upsert cdl;
            catch(Exception e){

Can anyone give an advise?