Last active
January 23, 2020 16:20
-
-
Save surajp/3a79e7b7deb29068effaddaec7c03b97 to your computer and use it in GitHub Desktop.
Generic method to delete a bunch of records while respecting profile and sharing access
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************************ | |
*** @author: Suraj Pillai | |
*** @group: Utils | |
*** @date: 01/2020 | |
*** @description: A class for deleting a bunch of records after checking for delete access for each sobject, given a list of recordIds | |
*/ | |
public with sharing class GenericDelete { | |
public class InsufficientPermissionsException extends Exception{} | |
/************************************************************ | |
*** @description Deletes a list of record ids, if the user has delete permissions | |
*** @param List<Id> recorIds - list of record ids to be deleted | |
*** @param boolean throwExceptionIfUndeletable - if one of the sobjects is not deleteable by the user, throw an exception | |
*** @return List<Id> - list of recordIds that were actually deleted | |
*/ | |
public Id[] doDelete(List<Id> recordIds,boolean throwExceptionIfUndeleteable){ | |
// sort the ids so same sobjects are grouped together | |
recordIds.sort(); | |
Id[] deletedIds = new Id[]{}; | |
String currentPrefix=''; | |
boolean currentIsDeleteable = false; | |
for(Id recordId: recordIds){ | |
String prefix = String.valueOf(recordId).subString(0,3); | |
//compare prefixes to see if the sobject has changed | |
if(prefix!=currentPrefix){ | |
currentIsDeleteable = false; | |
Schema.DescribeSObjectResult sobjDescribe = recordId.getSobjectType().getDescribe(); | |
if(!sobjDescribe.isDeletable()){ | |
if(throwExceptionIfUndeleteable){ | |
throw new InsufficientPermissionsException('Insufficient permissions to perform the requested action'); | |
} | |
}else{ | |
currentIsDeleteable = true; | |
} | |
} | |
else if(currentIsDeleteable){ | |
deletedIds.add(recordId); | |
} | |
currentPrefix = prefix; | |
} | |
if(deletedIds.size()>0) | |
Database.delete(deletedIds); | |
return deletedIds; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment