Deleting Any Object You Don’t Own

Each new Salesforce release has me revisiting previous solutions and looking at how they can be improved. One little tidbit that was provided in Winter ’13 is a way to get the SObject type from the Id. In the past, you’d have to do quite a bit of code to determine the type of SObject from the Id. Now all we need to do to get the SObject type from an ID is:


This got me thinking that I could rewrite my Contact deletion webservice and have it be more generic to delete any object I don’t own.

I call this SuperDelete. It is almost identical to my Contact deletion class except now it checks to see what the object type is first and instantiates a new object with that ID so it can be deleted. It then checks to see what access level the requesting user has. In this case, the user needs to have at least Edit Access.

global without sharing class SuperDelete {
webService static String deleteRecord(Id id) {
sObject so = id.getSObjectType().newSObject(id=id);
try {
UserRecordAccess ura = [select RecordId, HasEditAccess from UserRecordAccess where UserId = :UserInfo.getUserId() and RecordId = :id];
if (ura.HasEditAccess)
delete so;
throw new deleteException('Error deleting');
return '';
} catch (Exception e) {
return e.getMessage();

This webservice can be invoked from a custom JavaScript button that needs to be created on each object you want to use this on:


if (confirm("Are you sure?")) {
 var result = sforce.apex.execute("SuperDelete","deleteRecord", {id:"{!Contact.Id}"});
 var errorDiv = document.getElementById('errorDiv_ep');
 if (result != '') {
 errorDiv.innerHTML = result; = 'block';
 else window.location.replace('/003/o');

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s