Restrict Contact Deletion Based on User and Account Field Matching in Salesforce
Question:
How can I ensure that a Salesforce user can delete a Contact record only if the Contact’s Account field (Account.field__c) matches the User’s field (User.field__c)? The solution must also handle users with specific profiles.
Answer:
You can achieve this requirement using either Flows or Apex Triggers. Below, I’ll explain both methods:
Solution 1: Using Record-Triggered Flow
This is a declarative approach that leverages Salesforce’s Flow Builder.
Steps:
- Create a Record-Triggered Flow:
Object:Contact
Trigger:A record is deleted. - Set Entry Conditions: Add entry conditions if you want to limit when the flow runs (e.g., based on the user’s profile).
- Add a Decision Element:
Label:Same Office
Define two outcomes: - Add Actions for Outcomes:
For the Match path: Simply end the flow.
For the Mismatch path: Add a custom error action (e.g., “You cannot delete this Contact because your Booking Office does not match the Contact’s Account.”). - Assign Proper Permissions: Ensure users have delete permissions on the
Contactobject. - Test: Simulate deletions with users having matching and non-matching field values.
Solution 2: Using an Apex Trigger
For more advanced or customized requirements, use an Apex Trigger. Here’s an example:
Apex Trigger Example:
trigger RestrictContactDeletion on Contact (before delete) {
for (Contact con : Trigger.old) {
// Check the Account field and User field match
if (con.Account.field__c != UserInfo.getCustomField('field__c')) {
if (UserInfo.getProfileName() == 'HA Customer Care - External/Agents' ||
UserInfo.getProfileName() == 'HA Customer Care - Internal') {
con.addError('You cannot delete this Contact because your Booking Office does not match the Account Booking Office.');
}
}
}
}Explanation:
The trigger compares the Account.field__c value of the Contact being deleted to the current user’s User.field__c.
If they don’t match, and the user is part of the specified profiles, an error message is displayed, preventing the deletion.
Advantages of Using Apex:
Greater flexibility to handle complex conditions.
Can be extended to include additional logic as needed.

