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
Rafael.Martins.SantosRafael.Martins.Santos 

how validate if exist attachment?

Hi All,

I need create a validation to check if exist attachments in the opportunity.
Someone know if is possible to do that?

I need create something like that:
If Probability is =  75% , verify if exist at least 1 file attached in the opportunity, before the user proceed to the next stage.

Thanks
Rafael
 
HARSHIL U PARIKHHARSHIL U PARIKH
I understand your question ;)
These are the steps you can follow: (It can look like a lot but would work for sure)

1) First create a field named total_attachments__c on an Opportunity Object.
2) Go to Developer Console -> File --> New --> Apex Trigger.
3) Name it CountAttachOnOpp and choose SObject as Attachment
4) Now you will see the trigger got created with few lines of code. Get rid of those few lines of code and Copy and paste the below code.
5)
Trigger CountAttachOnOpp On Attachment (After Insert, After Update, After Delete, After UnDelete){
    
    List<Id> oppIds = New List<Id>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        
        For(Attachment att : Trigger.New){
            If(att.parentId != null && att.ParentId.getSObjectType() == Opportunity.getSObjectType()){
                oppIds.add(att.parentId);
            }
        }
    }
    If(Trigger.IsDelete){
        For(Attachment att : Trigger.Old){
            If(att.ParentId != null && att.ParentId.getSObjectType() == Opportunity.getSObjectType()){
                oppIds.add(att.ParentId);
            }
        }
    }
    
    List<Opportunity> oppFinalListToUpdate = New List<Opportunity>();
    
    List<Opportunity> FetchingEachOppFromOppIds = [Select Id, total_attachments__c, (Select ParentId FROM Attachments) FROM Opportunity WHERE Id = :oppIds];
    
    For(Opportunity EveryOpp : FetchingEachOppFromOppIds ){
        EveryOpp.total_attachments__c = EveryOpp.Attachments.size();
        oppFinalListToUpdate.add(EveryOpp);
    }
    
    try{
        If(!oppFinalListToUpdate.IsEmpty()){
            update oppFinalListToUpdate;
        }
    }
    Catch(Exception e){
        system.debug('Thrown Error: ' + e.getMessage());
    }
}
6) Now, create a validation rule on opportunity object with below formula:
AND( 

Probability >= 0.75, 
OR( 
ISBLANK(Total_Attachments__c ), 
Total_Attachments__c = 0 
) 

)

You are good to go!!

 
Rafael.Martins.SantosRafael.Martins.Santos
Hi Govind,

Thanks for your help
Varun Sachdeva 29Varun Sachdeva 29
Hi Govind,

The Code that you works perfectly fine in the sandbox. Can you help with the test classes?