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
Ricky SFDCRicky SFDC 

How to prevent record deletion based on certain condition?

Hi,
I am new to salesforce and i am facing an issue in writing a trigger.
The scenario is All the SALES user profile should be able to delete contact records except those records whose Status is Active.

Please help me in writing trigger.
Any help would be appreciated.

Thanks & Regards,
Ricky
Best Answer chosen by Ricky SFDC
Murali MattaMurali Matta
Hi Ricky,

Below code can help you.
trigger deleteContact on Contact(before delete) {

 Id profileId = userinfo.getProfileId();
 String profileName = [Select Id from Profile where Id =: profileId].Name;
 //if you are using Status field as picklist then write con.Status__c == 'Active'.
 //if you are using Status field as checkbox then write con.Status.
 for (Contact con: trigger.old) {
  if (profileName == 'Sales' && con.Status__c) {
   if (Trigger.isBefore) {

    if (Trigger.isDelete) {

     con.adderror('You cannot delete the record');

    }
   }
  }
 }

}
Let me know if you have any confusion..

Kindly mark this as solved if the reply was helpful.

Thanks,
Murali
 
 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi,

Below is the sample code 
 
Sample code is here 
Trigger PreventDelete on Account(before delete)
{ for(Account acc : Trigger.old) {
// Write your conditions here 
acc.addError('Deletion of Accountis disabled');
 }
 }

Best Regards,
Sandhya
Murali MattaMurali Matta
Hi Ricky,

Below code can help you.
trigger deleteContact on Contact(before delete) {

 Id profileId = userinfo.getProfileId();
 String profileName = [Select Id from Profile where Id =: profileId].Name;
 //if you are using Status field as picklist then write con.Status__c == 'Active'.
 //if you are using Status field as checkbox then write con.Status.
 for (Contact con: trigger.old) {
  if (profileName == 'Sales' && con.Status__c) {
   if (Trigger.isBefore) {

    if (Trigger.isDelete) {

     con.adderror('You cannot delete the record');

    }
   }
  }
 }

}
Let me know if you have any confusion..

Kindly mark this as solved if the reply was helpful.

Thanks,
Murali
 
 
This was selected as the best answer
Ricky SFDCRicky SFDC
Hi Sandhya & Murali,
Thanks for replying, really appreciate your efforts.