I want to give delete access to some set of users in certain condition to some records. I don't want to do this using profiles/permission sets. I want to achieve this using apex. Could anyone please give me an idea to write a trigger?
Delete access to a record requires one of the these items:
- Modify All
- System admin
- Owner of record
- Higher in the role hierarchy than the current owner
Assuming that you don't want to use Modify All permissions for users and assuming the user is not a member of a role higher than the record's owner; you are left with ....
Once the user chooses the record to delete, publish a Platform Event using Process Builder, Visual Flow or Apex.
The platform event might look like this:
DeleteMe__e with custom field (type Text, length 18)
Define a consumer for the Platform Event (again, using Process Builder, Visual Flow, or Apex trigger). This consumer will execute as Automated process user (and such user has Modify All) and can delete the record in question identified by the Id in question.