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
Mila JohnsonMila Johnson 

Need to limit all users (including admins) from deleting accounts except for one or two users?

We have a before delete trigger on the account to prevent account deletion for all. So how can we make an exception for just one or two users?


trigger preventAccountDeletion on Account (before delete) {

    for(Account acc : trigger.old){
       
        acc.adderror('Account Cannot be deleted');
    }

}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Mila,

You can get the user information i'e user id from UserInfo.getUserId() and if that does not match with that id you can add the above acc.adderror method as below.
 
trigger preventAccountDeletion on Account (before delete) {

    for(Account acc : trigger.old){ 
If(UserInfo.getUserId()!='some user id'){
       
        acc.adderror('Account Cannot be deleted');
    }
}

}
Let me know if you face any issue.

If this solution helps, Please mark it as best answer.

Thanks,

 
Mila JohnsonMila Johnson
Thanks for your reply!
Can we use username instead?

And if we need to add more users to this trigger in the future how can we do that?
mukesh guptamukesh gupta
Hi Mila,

You need to add user Id in  custom metadata and can compare in  trigger. in future i fyou want to increase number of user then you don't need to touch trigger just add new user ids in metadata

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 
Mila JohnsonMila Johnson
Hi Mukesh,  
Thanks for your reply!
I'm new to triggers, can you please guide me on how to do that.

OR (If you could help me with this)
the other solution I want to implement is having a checkbox on the User object and when true it will let them bypass the trigger. 

Mila.
Gregory StellarGregory Stellar
I found a great solution! And then there was a similar problem! Of course, I am constantly busy in plastic surgery here (https://celebrityweeks.com), cosmetic practice, but often here on the forum I find my answers!