+ Start a Discussion
Peter BölkePeter Bölke 

Trigger on Opportunity / Files

Hello,

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)
        {
            System.debug(cv);
            if(cv.ContentDocumentId != null)
            {
                contentDocumentIdSet.add(cv.ContentDocumentId);
            }
        }
        
        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);
        System.debug(checkId.getSobjectType());
        if(checkId.getSobjectType() == Opportunity.sObjectType){
            System.debug('Links ' + cd);
            List<ContentDocumentLink> cdl = new List<ContentDocumentLink>();
            try{

                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;
                        cdl.add(c);
                    }
                }
                upsert cdl;
                
            }
            catch(Exception e){
                System.debug(e);
            }
        }
    }
}

Can anyone give an advise?

thanks
Peter