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
SFDC pvSFDC pv 

How to prevent users from attaching the documents under Notes & Attachment related list when the Opportunity status is Approved via Apex class

Best Answer chosen by SFDC pv
Narender Singh(Nads)Narender Singh(Nads)
Hi,
You will have to write a trigger. Your trigger will look something like this:
trigger PreventAttachments on Attachment (before insert) {
    
    system.debug('Trigger called');
    
	Attachment a=trigger.new[0];
	if(string.valueOf(a.ParentId).startsWith('006')){
        opportunity o=[select stagename from opportunity where id=:a.ParentId];
        if(o.StageName=='Approved')
            a.adderror('Cannot add attachment');
    }
}

Note: You will have to write a similar trigger on Note if you want same validation for notes as well.

Please mark it as the best if it helps you.
Thanks

All Answers

Narender Singh(Nads)Narender Singh(Nads)
Hi,
You will have to write a trigger. Your trigger will look something like this:
trigger PreventAttachments on Attachment (before insert) {
    
    system.debug('Trigger called');
    
	Attachment a=trigger.new[0];
	if(string.valueOf(a.ParentId).startsWith('006')){
        opportunity o=[select stagename from opportunity where id=:a.ParentId];
        if(o.StageName=='Approved')
            a.adderror('Cannot add attachment');
    }
}

Note: You will have to write a similar trigger on Note if you want same validation for notes as well.

Please mark it as the best if it helps you.
Thanks
This was selected as the best answer
Satya Prakash ChoudharySatya Prakash Choudhary
Hi,

You can try to have different opportunity pagelaout and recordtype for Approved ones. In this pagelayout, don't show the Note and Attachement in related list. But this will also make user not able to check any previous notes.
SFDC pvSFDC pv
Hi @Narender Singh , I have tried the code you provided and tried other way also it's allowing me to attach the documents and log is also not captured.So I couldn't identify where it went wrong. Any suggestion pls 
Narender Singh(Nads)Narender Singh(Nads)
I tried the code on my org, and it is behaving as it should. Make sure you are testing the code with opportunirty with stage Approved. 
SFDC pvSFDC pv
Hi @Narender Singh, I have found out the issue. The problem is my Org is in LIghtning mode so when the org is in Lightning mode trigger should be written on ContentDocumentLink its working fine now. Thanks for your help .
Narender Singh(Nads)Narender Singh(Nads)
Please mark a best answer if it helped you so that others having same requirement can benefit from this post. 

Regards,
Narender