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
Shannan Robillard 2Shannan Robillard 2 

trigger to update a checkbox when certain files are uploaded

New to Apex coding so I am hoping that the community can help me. I am trying to create a trigger from Files that will check a custom checkbox field on the Opportunity when two Executed documents are uploaded to the related "Files" list. Here is what I have so far: 

trigger ContentDocumentLinkTrigger on ContentDocumentLink (before insert, before delete)
{
if(trigger.isinsert){
List<Opportunity> co = [select id from Opportunity where id =: Trigger.New[0].Id];
If(co.size()>0)        
{            
co[0].Executed_Docs_Attached__c = True;            
update co;        
}
}


if(trigger.isdelete){

List<Opportunity> co = [select id from Opportunity where id =: Trigger.old[0].Id];        
If(co.size()>0)        
{            
co[0].Executed_Docs_Attached__c = false;            
update co;        
}
}
}
However, this code is not updating the checkbox and I am not sure how or if I can specify to only update the checkbox if the file name has "Executed" included. Any thoughts would helpful. 
Thanks
Shruti SShruti S
Could you please try the below code: 
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( after INSERT, before DELETE ) {
    List<String> linkedEntIds = new List<String>();
    
    for( ContentDocumentLink link : Trigger.new ) {
        linkedEntIds.add( link.LinkedEntityId );
    }
    
    List<ContentDocumentLink> conDocLinks = new List<ContentDocumentLink>();
    conDocLinks = [
        SELECT  LinkedEntityId
        FROM    ContentDocumentLink
        WHERE   Id IN :Trigger.newMap.keyset()
        AND     LinkedEntity.Type = 'Opportunity' 
        AND     ContentDocument.Title LIKE '%Executed%'
        AND     LinkedEntityId IN :linkedEntIds
    ];
    
    if( !conDocLinks.isEmpty() ) {
        List<Opportunity> oppsToUpdate = new List<Opportunity>();
        
        for( ContentDocumentLink conDocLink : conDocLinks ) {
            Opportunity opp = new Opportunity();
            
            opp.Id                          = conDocLink.LinkedEntityId;
            opp.Executed_Docs_Attached__c   = Trigger.isInsert;
            
            oppsToUpdate.add( opp );
        }
        
        UPDATE oppsToUpdate;
    }
}
Rishi Kumar 135Rishi Kumar 135
Hi Shruti,
Thank you for shaing the code but it is not working if we deleted the file.
 
Marek Demiš 10Marek Demiš 10
Hello Shruti,

i tried your code in my case and everything works perfectly! Currenty i have problem with code coverage when iam deploying. Could i ask you for an example of your test class?

Thank you for you response

Mark